自定义异常
- 使用Java内置的异常类可以描述在变成时出现的大部分异常情况。除此之外, 用户还可以自定义异常。用户自定义异常类, 只需继承Exception类即可。
- 在程序中使用自定义异常类, 大体可分为以下几个步骤:
- 在创建自定义异常类。
- 在方法中通过throw关键字抛出异常对象。
- 如果当前抛出异常的方法中处理异常, 可以使用try-catch语句捕获并处理;否则在方法的声明处通过throws关键字指明要抛出给方法调用者的异常, 继续进行下一步操作。
- 在出现异常方法的调用者中并捕获并处理异常。
public class Application{
public static void main(String[] args) {
try {
test(1);
} catch (TestException e) {
System.out.println("MyException=>"+e);
}
}
static void test(int a) throws TestException {
System.out.println("start");
if (a > 10) {
throw new TestException(a);
}
System.out.println("end");
}
}
class TestException extends Exception {
private int detail;
public TestException(int detail) {
this.detail = detail;
}
@Override
public String toString() {
return "TestException{" +
"detail=" + detail +
'}';
}
}
实际应用中的经验总结
- 处理运行时异常时, 采用逻辑去合理规避同时辅助try-catch处理
- 在多重catch块后面, 可以加一个catch(Exception)来处理可能会被遗漏的异常
- 对于不确定的代码, 也可以加上try-catch, 处理潜在的异常
- 尽量去处理异常, 切忌只是简单地调用printStackTrace()去打印输出
- 具体如何处理异常, 要根据不同的业务需求和异常类型去决定
- 尽量添加finally语句去释放占用的资源
public class CUSTOMIZEException extends RuntimeException {
private static final long serialVersionUID = 1L;
private String msg;
private int code = 500;
public CUSTOMIZEException (String msg) {
super(msg);
this.msg = msg;
}
public CUSTOMIZEException (String msg, Throwable e) {
super(msg, e);
this.msg = msg;
}
public CUSTOMIZEException (String msg, int code) {
super(msg);
this.msg = msg;
this.code = code;
}
public CUSTOMIZEException (String msg, int code, Throwable e) {
super(msg, e);
this.msg = msg;
this.code = code;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
public int getCode() {
return code;
}
public void setCode(int code) {
this.code = code;
}
}