try {
// Your code that may throw an exception
}
catch (ExceptionClass1 e1){
// Handle exception of ExceptionClass1 type
}
catch (ExceptionClass2 e2){
// Handle exception of ExceptionClass2 type
}
catch (ExceptionClass3 e3){
// Handle exception of ExceptionClass3 type
}
例子
下面的代碼顯示了如何處理除零異常。
public class Main {
public static void main(String[] args) {
int x = 10, y = 0, z;
try {
z = x / y;
System.out.println("z = " + z);
} catch (ArithmeticException e) {
String msg = e.getMessage();
System.out.println("The error is: " + msg);
}
System.out.println("The end.");
}
}
更多建議: