异常的祖祖辈辈

工作中接触的一般都是Exception下的异常,在常规业务处理中,一般会把异常集中归类,例如一个项目中新建一个自定义异常的鼻祖:BaseException ,并且让这个鼻祖继承RuntimeException,构造器也都写上,例如下方:
package com.wx.Exception.custom;
public class BaseException extends RuntimeException {
public BaseException() {
}
public BaseException(String message) {
super(message);
}
public BaseException(String message, Throwable cause) {
super(message, cause);
}
public BaseException(Throwable cause) {
super(cause);
}
public BaseException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {
super(message, cause, enableSuppression, writableStackTrace);
}
}
然后呢,其他的业务异常就统统的称这个BaseException为祖先了。
package com.wx.Exception.custom;
public class NoSeeException extends BaseException {
NoSeeException(String path, String reason) {
super(path + ((reason == null)
? ""
: " (" + reason + ")"));
}
}
最后,体验一把喽。
package com.wx.Exception.custom;
public class Test {
public static void main(String[] args) {
b();
System.out.println("111111111111111");
a();
}
public static String b(){
String result = "";
try {
a();
System.out.println(">>>>>>>>>>>>>>>>");
} catch (Exception e) {
System.out.println("-------------");
e.printStackTrace();
}
return result;
}
public static String a() throws NoSeeException{
throw new NoSeeException("谁动了我的奶酪","没空");
}
}
本文详细介绍了在Java项目中如何创建和使用自定义异常。通过继承RuntimeException,构建了一个基础异常类BaseException,随后在此基础上创建了具体的业务异常NoSeeException。文章通过示例代码展示了异常的抛出和捕获过程。
2630

被折叠的 条评论
为什么被折叠?



