Java如何捕获多个异常?
如果try块可以引发几种不同类型的异常,而您想以不同方式处理每个异常,则可以放置多个catch块来处理它。
package org.nhooo.example.fundamental;
public class MultipleCatchExample {
public static void main(String[] args) {
int[] numbers1 = {1, 2, 3, 4, 5};
int[] numbers2 = {1, 2, 3, 4, 5, 6};
try {
//该行抛出ArrayIndexOutOfBoundsException
MultipleCatchExample.printResult(numbers1);
//该行抛出ArithmeticException
MultipleCatchExample.printResult(numbers2);
} catch (ArithmeticException e) {
e.printStackTrace();
} catch (ArrayIndexOutOfBoundsException e) {
e.printStackTrace();
} finally {
System.out.println("Finally block is always executed.");
}
}
/**
* Divide the given first number by the second number.
*
* @param x the first number.
* @param y the second number.
* @return the result of division.
*/
private static int divide(int x, int y) {
return x / y;
}
/**
* Print the output result of divide operation by calling the
* divide() method.
*
* @param numbers integer arrays of the divided number
* @throws ArrayIndexOutOfBoundsException when an exception
* occurs.
*/
private static void printResult(int[] numbers) {
int x, z, y = 1;
for (int i = 0; i < 6; i++) {
x = numbers[i];
if (i == 5) {
y = 0;
}
z = MultipleCatchExample.divide(x, y);
System.out.println("z = " + z);
}
}
}
热门推荐
10 祝孙辈生日祝福语简短
11 恋人跨年祝福语大全简短
12 考大学敬酒简短祝福语
13 开工投产大吉祝福语 简短
14 偶然结婚祝福语朋友简短
15 感谢学长学姐祝福语简短
16 戏精的祝福语简短
17 我要结婚祝福语简短
18 婚前女儿生日祝福语简短