java异常处理

  • 在java中有一个很厉害的类。叫做Throwable类,在Java中Exception和Error类继承这个类;Error非常严重,称为致命性异常;Exception类称为非致命性错误,广义的可以定义为RunTtimeException类和其他异常类,我们一般捕获的都是RunTtimeException
  • 异常:程序运行过程中由于打开不存在的文件或者3/0时出现异常,阻塞程序正常执行
  • 异常的捕获
try{
} catch(Exception1 e1) {
    // 在这里定义特定的Exception,处理特殊情况
} catch(Exception e){
    // 输出异常信息
    e.printStackTrace(e);
} finally{
    // 程序块,一般关闭文件或者各种流
}
  • e实例的方法
e.getMessage()  // 输出错误性质
e.toString()    // 给出异常的类型与性质
e.printStackTrace()   // 输出类型、性质、栈的层次以及出现异常位置
  • finally语句块:一般情况下一定会执行,下面的情况不会执行
1.finally语句块中出现了异常
2.前面的代码中使用了System.out()退出了程序
3.程序所在的线程死亡
4.关闭CPU
  • 自定义异常
在程序中使用自定义异常,大体分为以下几个步骤:
1.自定义异常,继承于Exception类
2.在方法中通过throw关键字抛出自定义的异常
3.使用try-catch语句捕获异常或者抛出给上层
4.在出现异常的调用者中捕获异常并处理异常

// 继承Exception
class MyException extends Exception{
    public MyException(String ErrorMessage){
        super(ErrorMessage);  // 调用父类的构造方法,自定义异常信息
    }
}

-------------------------------示例----------------------------------
// 通过继承Exception类并且实现自定义的CommonError接口,实现项目通用化的异常
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;
    }
}

// 定义CommonError类,主要是为了自定义错误码和错误信息
public interface CommonError {

    public int getErrorCode();
    public String getErrorMsg();
    public CommonError setErrorMsg(String ErrMsg);
}


// 自定义EmBusinessError类,通过throw new BusinessException(EmBusinessError.UNKNOW_ERROR)形式抛出异常
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;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值