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"