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 婆婆高寿祝福语大全简短