Skip to content
On this page

错误

捕获错误

自定义 类

java
class  User {
 public void test(int x,int y) throws ArithmeticException {
    System.out.println(x / y);
 }

使用 u.test 加上 .try 自动添加错误信息

测试类

java
User u = new User();
try {
  u.test(1,0);
} catch (ArithmeticException e) {
  e.printStackTrace();
}

捕获多种异常

如果某些异常的处理逻辑相同,但是异常本身不存在继承关系,那么就得编写多条catch子句:

java
public static void main(String[] args) {
    try {
        process1();
        process2();
        process3();
    } catch (IOException e) {
        System.out.println("Bad input");
    } catch (NumberFormatException e) {
        System.out.println("Bad input");
    } catch (Exception e) {
        System.out.println("Unknown error");
    }
}

因为处理 IOExceptionNumberFormatException 的代码是相同的,所以我们可以把它两用|合并到一起:

java
public static void main(String[] args) {
    try {
        process1();
        process2();
        process3();
    } catch (IOException | NumberFormatException e) { // IOException或NumberFormatException
        System.out.println("Bad input");
    } catch (Exception e) {
        System.out.println("Unknown error");
    }
}