一:异常的分类

异常的体系结构

QQ截图20210110210033.png

1. 编译时异常(在编译时出现的异常,即编写代码时java自带的类抛出的异常)

2. 运行时异常 (在编译(javac)时不会抛出异常,在解释运行(java)时会出现的异常)

二:异常的抛出throws(最高抛到main方法,main方法如果不try catch的话就会终止程序的运行,必须有一个类进行try catch)

  1. try-catch如果匹配的异常对象不否和,就相当于感冒吃治便秘的药,没有对症下药。
  2. 如果异常之间存在子父类关系,子类必须在上,父类在上会报错,如下代码不会运行
  3. throws关键字(表示可能会有异常抛出) 抛出异常
  4. 子类抛出的异常不能大于父类抛出的异常
  1. //错误示范
  2. @Test
  3. public void Test01() {
  4. String str = "123";
  5. str = "abc";
  6. int num = 0;
  7. try {
  8. num = Integer.parseInt(str);
  9. } catch (Exception e) {
  10. System.out.println("出现数字格式异常");
  11. } catch (NumberFormatException e) {
  12. System.out.println("出现数字格式异常");
  13. }
  14. System.out.println(num);
  15. }
  16. //正确示范
  17. @Test
  18. public void Test01() {
  19. String str = "123";
  20. str = "abc";
  21. int num = 0;
  22. try {
  23. num = Integer.parseInt(str);
  24. } catch (NumberFormatException e) {
  25. System.out.println("出现数字格式异常");
  26. } catch (Exception e) {
  27. System.out.println("出现数字格式异常");
  28. }
  29. System.out.println(num);
  30. }

1. 处理异常示例

处理文件FileNotFoundException和 IOException

  1. @Test
  2. public void Test02(){
  3. File file = new File("a.txt");
  4. try {
  5. FileInputStream inputStream = new FileInputStream(file);
  6. int read = inputStream.read();
  7. while (read != -1) {
  8. System.out.println((char) read);
  9. inputStream.read();
  10. }
  11. inputStream.close();
  12. } catch (FileNotFoundException e) {
  13. String message = e.getMessage();
  14. System.out.println(message);
  15. }catch (IOException e){
  16. String message = e.getMessage();
  17. System.out.println(message);
  18. }
  19. }

2.finally的执行优先级(finally会在return之前执行)!!!

  1. public int Test01(){
  2. try {
  3. int[] ints = new int[50];
  4. System.out.println(ints[51]);
  5. return 1;
  6. } catch (ArrayIndexOutOfBoundsException e) {
  7. // String message = e.getMessage();
  8. // System.out.println(message);
  9. e.printStackTrace();
  10. return 2;
  11. } finally {
  12. System.out.println("我的优先级");
  13. }
  14. }
  15. @Test
  16. public void Test02(){
  17. int i = Test01();
  18. System.out.println(i);
  19. }