一:异常的分类
异常的体系结构
1. 编译时异常(在编译时出现的异常,即编写代码时java自带的类抛出的异常)
2. 运行时异常 (在编译(javac)时不会抛出异常,在解释运行(java)时会出现的异常)
二:异常的抛出throws(最高抛到main方法,main方法如果不try catch的话就会终止程序的运行,必须有一个类进行try catch)
- try-catch如果匹配的异常对象不否和,就相当于感冒吃治便秘的药,没有对症下药。
- 如果异常之间存在子父类关系,子类必须在上,父类在上会报错,如下代码不会运行
- throws关键字(表示可能会有异常抛出) 抛出异常
- 子类抛出的异常不能大于父类抛出的异常
//错误示范@Testpublic void Test01() {String str = "123";str = "abc";int num = 0;try {num = Integer.parseInt(str);} catch (Exception e) {System.out.println("出现数字格式异常");} catch (NumberFormatException e) {System.out.println("出现数字格式异常");}System.out.println(num);}//正确示范@Testpublic void Test01() {String str = "123";str = "abc";int num = 0;try {num = Integer.parseInt(str);} catch (NumberFormatException e) {System.out.println("出现数字格式异常");} catch (Exception e) {System.out.println("出现数字格式异常");}System.out.println(num);}
1. 处理异常示例
处理文件FileNotFoundException和 IOException
@Testpublic void Test02(){File file = new File("a.txt");try {FileInputStream inputStream = new FileInputStream(file);int read = inputStream.read();while (read != -1) {System.out.println((char) read);inputStream.read();}inputStream.close();} catch (FileNotFoundException e) {String message = e.getMessage();System.out.println(message);}catch (IOException e){String message = e.getMessage();System.out.println(message);}}
2.finally的执行优先级(finally会在return之前执行)!!!
public int Test01(){try {int[] ints = new int[50];System.out.println(ints[51]);return 1;} catch (ArrayIndexOutOfBoundsException e) {// String message = e.getMessage();// System.out.println(message);e.printStackTrace();return 2;} finally {System.out.println("我的优先级");}}@Testpublic void Test02(){int i = Test01();System.out.println(i);}
