Java中的多个捕获
为了捕获单个try块生成的不同异常,我们在Java中使用了多个catch块。
多捕获块的语法如下-
try {
}
catch(Exception1 | Exception2 | Exception3…..| ExceptionN exception_obj)
{
}让我们看看Java中用于多个catch块的程序-
示例
import java.util.Scanner;
public class Example {
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
try {
int n = Integer.parseInt(sc.next());
System.out.println(n/0);
}
catch (ArithmeticException | NumberFormatException e) {
System.out.println("Exception Caught: " + e);
}
}
}输出取决于输入。
对于以下输入-
5
输出结果
对于以下输入-
Exception Caught: java.lang.ArithmeticException: / by zero
Hello
输出结果
Exception Caught: java.lang.NumberFormatException: For input string: "Hello"
热门推荐
10 儿子立冬祝福语简短独特
11 对当兵的祝福语简短
12 侄儿高考试祝福语简短
13 伴郎红包祝福语朋友简短
14 媳妇生日简短祝福语朋友
15 公司年会祝福语简短最好
16 元旦感恩祝福语简短大全
17 红包祝福语简短10字
18 周六早晨祝福语简短