JavaSE—异常

1、try-catch

public class Demo2 {

	public static void main(String[] args) {
		FileInputStream input=null;
		try {
			input=new FileInputStream("C://a.txt");
			int data;
			while((data=input.read())!=-1) {
				System.out.println((char)data);
			}
		} catch (Exception e) {
			System.out.println("异常:"+e.getMessage());
		}
	}
	/**
	 * 输出:异常:C:\a.txt (系统找不到指定的文件。)
	 */
}

2、异常的基本处理流程

  • 出错时,将异常抛出给调用代码:throw new Exception("类型转换错误!");
  • 当在外调用时,将上述抛出的异常用 try—catch 捕获;

3、异常的运行规则

  • 在try块中出现异常,退出try,进入catch;
  • 如果没有匹配到对应的catch,则退出当前方法,将异常抛出给上一层处理;
  • 如果最终异常没有被捕获,那么程序会崩溃;

4、退出清理

  • 用到finally,不再赘述;

猜你喜欢

转载自blog.csdn.net/dyz4001/article/details/82730291