Skip to content

Latest commit

 

History

History
181 lines (139 loc) · 6.98 KB

0-异常与异常类.md

File metadata and controls

181 lines (139 loc) · 6.98 KB

异常与异常类

1.异常的概念

导致程序的正常流程被中断的事件,叫做异常

在计算机程序运行的过程中,总是会出现各种各样的错误。

有一些错误是用户造成的,比如,希望用户输入一个int类型的年龄,但是用户的输入是abc

// 假设用户输入了abc:
String s = "abc";
int n = Integer.parseInt(s); // NumberFormatException!

程序想要读写某个文件的内容,但是用户已经把它删除了:

// 用户删除了该文件:
String t = readFile("C:\\abc.txt"); // FileNotFoundException!

还有一些错误是随机出现,并且永远不可能避免的。比如:

  • 网络突然断了,连接不到远程服务器;
  • 内存耗尽,程序崩溃了;
  • ……

所以,一个健壮的程序必须处理各种各样的错误。

所谓错误,就是程序调用某个函数的时候,如果失败了,就表示出错。

2.如何得知错误信息

调用方如何获知调用失败的信息?有两种方法:

方法一:约定返回错误码。

例如,处理一个文件,如果返回0,表示成功,返回其他整数,表示约定的错误码:

int code = processFile("C:\\test.txt");
if (code == 0) {
    // ok:
} else {
    // error:
    switch (code) {
    case 1:
        // file not found:
    case 2:
        // no read permission:
    default:
        // unknown error:
    }
}

因为使用int类型的错误码,想要处理就非常麻烦。这种方式常见于底层C函数。

方法二:在语言层面上提供一个异常处理机制。

Java内置了一套异常处理机制,总是使用异常来表示错误。

异常是一种类,因此它本身带有类型信息。异常可以在任何地方抛出,但只需要在上层捕获(下面的例子是使用try-catch捕获),这样就和方法调用分离了:

try {
    String s = processFile(“C:\\test.txt”);
    // ok:
} catch (FileNotFoundException e) {
    // file not found:
} catch (SecurityException e) {
    // no read permission:
} catch (IOException e) {
    // io error:
} catch (Exception e) {
    // other error:
}

3.异常的分类

Java异常的继承关系如下:

                     ┌───────────┐
                     │  Object   │
                     └───────────┘
                           ▲
                           │
                     ┌───────────┐
                     │ Throwable │
                     └───────────┘
                           ▲
                 ┌─────────┴─────────┐
                 │                   │
           ┌───────────┐       ┌───────────┐
           │   Error   │       │ Exception │
           └───────────┘       └───────────┘
                 ▲                   ▲
         ┌───────┘              ┌────┴──────────┐
         │                      │               │
┌─────────────────┐    ┌─────────────────┐┌───────────┐
│OutOfMemoryError │... │RuntimeException ││IOException│...
└─────────────────┘    └─────────────────┘└───────────┘
                                ▲
                    ┌───────────┴─────────────┐
                    │                         │
         ┌─────────────────────┐ ┌─────────────────────────┐
         │NullPointerException │ │IllegalArgumentException │...
         └─────────────────────┘ └─────────────────────────┘

从继承关系可知:Throwable是异常体系的根,它继承自ObjectThrowable有两个体系:ErrorExceptionError表示严重的错误,程序对此一般无能为力,例如:

  • OutOfMemoryError:内存耗尽
  • NoClassDefFoundError:无法加载某个Class
  • StackOverflowError:栈溢出

Exception则是运行时的错误,它可以被捕获并处理。

某些异常是应用程序逻辑处理的一部分,应该捕获并处理。例如:

  • NumberFormatException:数值类型的格式错误
  • FileNotFoundException:未找到文件
  • SocketException:读取网络失败

还有一些异常是程序逻辑编写不对造成的,应该修复程序本身。例如:

  • NullPointerException:对某个null的对象调用方法或字段
  • IndexOutOfBoundsException:数组索引越界

Exception又分为两大类:

  1. RuntimeException以及它的子类;
  2. RuntimeException(包括IOExceptionReflectiveOperationException等等)

Java规定:

  • 必须捕获的异常,包括Exception及其子类,但不包括RuntimeException及其子类,这种类型的异常称为Checked Exception(可查异常)。可查异常遵循“谁调用,谁处理”,比如FileNotFoundException,如果不处理,编译器就不允许通过。

    public class Main{
        public static void main(String[] args) {
            File f= new File("a.txt");
            try{
                System.out.println("read a.txt");
                new FileInputStream(f);
                System.out.println("success");
            }
            catch(FileNotFoundException e){
                System.out.println("a.txt do not exist");
                e.printStackTrace();
            }   
        }
    }
    
  • 不需要捕获的异常,包括Error及其子类,RuntimeException及其子类。

    • 实际上对于运行时异常,在编写代码的时候,依然可以使用try-catch或 throws进行处理,与可查异常不同之处在于,即便不进行try catch,也不会有编译错误。Java之所以会设计运行时异常的原因之一,是因为下标越界,空指针这些运行时异常太过于普遍,如果都需要进行捕捉,代码的可读性就会变得很糟糕。

      public class Main {  
          public static void main(String[] args) {
              //任何除数不能为0:ArithmeticException
              int k = 5/0;
              //下标越界异常:ArrayIndexOutOfBoundsException
              int j[] = new int[5];
              j[10] = 10;
              //空指针异常:NullPointerException
              String str = null;
              str.length();
         }
      }
      

注意:编译器对RuntimeException及其子类不做强制捕获要求,不是指应用程序本身不应该捕获并处理RuntimeException。是否需要捕获,具体问题具体分析。