如何在 JAVA 中捕获两个或多个异常?
How to catch two or more Exceptions in JAVA?
如何同时捕获 2 个或更多异常?我应该为每个问题使用 trycatch-block 吗?
例如,我无法在 arithmeticException 之后捕获 b.charAt() 到“空指针异常”。
try{
int a = 6 / 0 ;
String b = null;
System.out.println(b.charAt(0));
}
catch(NullPointerException e){
System.out.println("Null Pointer Exception");
}
catch(ArithmeticException e){
System.out.println("Aritmetic Exception ");
}
在 Java SE 7 及更高版本中,您实际上可以在同一个 catch 块中捕获多个异常。
要做到,你这样写:
try{
// Your code here
} catch (ExampleException1 | ExampleException2 | ... | ExampleExceptionN e){
// Your handling code here
}
除此之外,您还可以使用非常通用的捕获异常,例如:
try{
// code here
} catch (Exception e){
// exception handling code here
}
但是,这是一种令人气馁的做法。 ;)
资源:https://docs.oracle.com/javase/tutorial/essential/exceptions/catch.html(Oracle 文档)。
如何同时捕获 2 个或更多异常?我应该为每个问题使用 trycatch-block 吗?
例如,我无法在 arithmeticException 之后捕获 b.charAt() 到“空指针异常”。
try{
int a = 6 / 0 ;
String b = null;
System.out.println(b.charAt(0));
}
catch(NullPointerException e){
System.out.println("Null Pointer Exception");
}
catch(ArithmeticException e){
System.out.println("Aritmetic Exception ");
}
在 Java SE 7 及更高版本中,您实际上可以在同一个 catch 块中捕获多个异常。
要做到,你这样写:
try{
// Your code here
} catch (ExampleException1 | ExampleException2 | ... | ExampleExceptionN e){
// Your handling code here
}
除此之外,您还可以使用非常通用的捕获异常,例如:
try{
// code here
} catch (Exception e){
// exception handling code here
}
但是,这是一种令人气馁的做法。 ;)
资源:https://docs.oracle.com/javase/tutorial/essential/exceptions/catch.html(Oracle 文档)。