- 在java中有一个很厉害的类。叫做Throwable类,在Java中Exception和Error类继承这个类;Error非常严重,称为致命性异常;Exception类称为非致命性错误,广义的可以定义为RunTtimeException类和其他异常类,我们一般捕获的都是RunTtimeException
- 异常:程序运行过程中由于打开不存在的文件或者3/0时出现异常,阻塞程序正常执行
- 异常的捕获
try{
} catch(Exception1 e1) {
} catch(Exception e){
e.printStackTrace(e);
} finally{
}
e.getMessage()
e.toString()
e.printStackTrace()
- finally语句块:一般情况下一定会执行,下面的情况不会执行
1.finally语句块中出现了异常
2.前面的代码中使用了System.out()退出了程序
3.程序所在的线程死亡
4.关闭CPU
在程序中使用自定义异常,大体分为以下几个步骤:
1.自定义异常,继承于Exception类
2.在方法中通过throw关键字抛出自定义的异常
3.使用try-catch语句捕获异常或者抛出给上层
4.在出现异常的调用者中捕获异常并处理异常
class MyException extends Exception{
public MyException(String ErrorMessage){
super(ErrorMessage);
}
}
-------------------------------示例----------------------------------
public class BusinessException extends Exception implements CommonError {
private CommonError commonError;
public BusinessException(CommonError commonError){
super();
this.commonError = commonError;
}
public BusinessException(CommonError commonError, String errMsg){
super();
this.commonError = commonError;
this.commonError.setErrorMsg(errMsg);
}
@Override
public int getErrorCode() {
return this.commonError.getErrorCode();
}
@Override
public String getErrorMsg() {
return this.commonError.getErrorMsg();
}
@Override
public CommonError setErrorMsg(String ErrMsg) {
this.commonError.setErrorMsg(ErrMsg);
return this;
}
}
public interface CommonError {
public int getErrorCode();
public String getErrorMsg();
public CommonError setErrorMsg(String ErrMsg);
}
public enum EmBusinessError implements CommonError {
UNKNOW_ERROR(100001, "未知错误"),
;
private EmBusinessError(int errCode, String errMsg){
this.errCode = errCode;
this.errMsg = errMsg;
}
private int errCode;
private String errMsg;
@Override
public int getErrorCode() {
return this.errCode;
}
@Override
public String getErrorMsg() {
return this.errMsg;
}
@Override
public CommonError setErrorMsg(String ErrMsg) {
this.errMsg = ErrMsg;
return this;
}
}