try{
// 可能发⽣异常的代码
}catch(AExceptionName e){
//出异常的时候处理
}catch(BExceptionName e){
}fianall{
}
一个try代码块后面跟多个catch代码块的情况就叫多重捕获
try{
// 可能发⽣异常的代码
}catch(ExceptionName1 e1){
//出异常的时候处理
}catch(ExceptionName2 e2){
//出异常的时候处理
}
代码中发生异常,异常被抛给第一个catch块,如果不匹配则继续往下一个catch进行传递
try{
// 可能发⽣异常的代码
}catch(ExceptionName1 e1){
//出异常的时候处理
}finally{
//肯定执⾏的代码
}
或者
try{
// 可能发⽣异常的代码
}finally{
//肯定执⾏的代码
}
例子
public class Main {
public static void readChar() throws IOException,RemoteException {
int input = System.in.read();
}
}
语法
throw new ExceptionName("异常信息");
例子
throw new IOException("File not found");
当抛出异常被检查的异常,我们必须使用try-catch块来处理它,或者在方法声明中使用throws子句继续往外抛
例子
public class BaseException extends Exception {
private String errorMessage;
private String errorCode;
public BaseException(String errorCode, String errorMessage) {
super(errorMessage);
this.errorCode = errorCode;
this.errorMessage = errorMessage;
}
public String getErrorMessage() {
return errorMessage;
}
public String getErrorCode() {
return errorCode;
}
public void setErrorCode(String errorCode) {
this.errorCode = errorCode;
}
public void setErrorMessage(String errorMessage) {
this.errorMessage = errorMessage;
}
}