Java如何捕获多个异常

x33g5p2x  于2021-08-21 转载在 Java  
字(1.8k)|赞(0)|评价(0)|浏览(575)

在本教程中,我们将在实例的帮助下学习如何在Java中处理多个异常。
在Java 7之前,我们不得不为不同类型的异常编写多个异常处理代码,即使有代码冗余。

让我们举个例子。

例子1:多个catch块

class Main {
  public static void main(String[] args) {
    try {
      int array[] = new int[10];
      array[10] = 30 / 0;
    } catch (ArithmeticException e) {
      System.out.println(e.getMessage());
    } catch (ArrayIndexOutOfBoundsException e) {
      System.out.println(e.getMessage());
    } 
  }
}

输出

/ by zero

在这个例子中,可能会出现两个异常。

  • ArithmeticException 因为我们正试图用一个数字除以0。
  • ArrayIndexOutOfBoundsException 因为我们声明了一个新的整数数组,数组边界为0到9,我们试图给索引10分配一个值。

我们在catch块中都打印出了异常信息,即重复的代码。

赋值运算符=的关联性是从右到左,所以一个ArithmeticException首先被抛出,消息是/由0。


在一个catch块中处理多个异常

在Java SE 7及以后的版本中,我们现在可以在一个catch块中捕捉一种以上的异常类型。

每个可以由catch块处理的异常类型都用一个竖条或管子|来分隔。

其语法为:。

try {
  // code
} catch (ExceptionType1 | Exceptiontype2 ex) { 
  // catch block
}

例2:多抓取块

class Main {
  public static void main(String[] args) {
    try {
      int array[] = new int[10];
      array[10] = 30 / 0;
    } catch (ArithmeticException | ArrayIndexOutOfBoundsException e) {
      System.out.println(e.getMessage());
    }
  }
}

输出

/ by zero

在一个catch块中捕获多个异常,可以减少代码的重复,提高工作效率。

在编译这个程序时产生的字节码将比有多个catch块的程序要小,因为没有代码的冗余。

**注意:**如果一个catch块处理多个异常,那么catch参数就隐含了final。这意味着我们不能给catch参数分配任何值。


捕获基础异常

当在一个catch块中捕获多个异常时, 这个规则被概括为专门化。

这意味着,如果在catch块中有一个层次的异常,我们可以只捕捉基本的异常,而不是捕捉多个专门的异常。

让我们举个例子。

例子3:只捕捉基础异常类

class Main {
  public static void main(String[] args) {
    try {
      int array[] = new int[10];
      array[10] = 30 / 0;
    } catch (Exception e) {
      System.out.println(e.getMessage());
    }
  }
}

输出

/ by zero

我们知道,所有的异常类都是Exception类的子类。因此,我们可以简单地捕捉Exception类,而不是捕捉多个专门的异常。


如果在catch块中已经指定了基本的异常类,就不要在同一个catch块中使用子异常类。否则,我们将得到一个编译错误。

让我们举个例子。

例子4:捕捉基类和子类异常

class Main {
  public static void main(String[] args) {
    try {
      int array[] = new int[10];
      array[10] = 30 / 0;
    } catch (Exception | ArithmeticException | ArrayIndexOutOfBoundsException e) {
      System.out.println(e.getMessage());
    }
  }
}

输出

Main.java:6: error: Alternatives in a multi-catch statement cannot be related by subclassing

在这个例子中,ArithmeticExceptionArrayIndexOutOfBoundsException都是Exception类的子类。因此,我们得到一个编译错误。

相关文章