在本教程中,我们将在实例的帮助下学习如何在Java中处理多个异常。
在Java 7之前,我们不得不为不同类型的异常编写多个异常处理代码,即使有代码冗余。
让我们举个例子。
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。
在Java SE 7及以后的版本中,我们现在可以在一个catch
块中捕捉一种以上的异常类型。
每个可以由catch
块处理的异常类型都用一个竖条或管子|
来分隔。
其语法为:。
try {
// code
} catch (ExceptionType1 | Exceptiontype2 ex) {
// catch block
}
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
块中有一个层次的异常,我们可以只捕捉基本的异常,而不是捕捉多个专门的异常。
让我们举个例子。
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
块中使用子异常类。否则,我们将得到一个编译错误。
让我们举个例子。
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
在这个例子中,ArithmeticException
和ArrayIndexOutOfBoundsException
都是Exception
类的子类。因此,我们得到一个编译错误。
版权说明 : 本文为转载文章, 版权归原作者所有 版权申明
原文链接 : https://www.programiz.com/java-programming/multiple-exceptions
内容来源于网络,如有侵权,请联系作者删除!