每次抛出特定的自定义异常时,我都需要执行一个方法。执行的代码会将异常报告给我的API。异常类具有一个boolean
参数,该参数说明是否应报告该异常。假设我编码了以下异常:
public MyException extends Exception {
private final String message;
private final int code;
private final boolean report;
public MyException(String message, int code, boolean report) {
this.message = message;
this.code = code;
this.report = report;
}
public void report() {
if(report) {
// Report some stuff
}
}
}
当引发MyException
时,我希望执行report()
中的代码。我已经考虑过手动调用该方法:
try {
throw new MyException("Test", 1, true);
} catch(MyException e) {
e.report();
}
但是我想知道是否可以在引发异常时自动调用该函数。
...
throw new MyExcepion("Test", 1, true); // Implicitlly calls report()
...
请注意,我不想在异常实例化时调用它,因为这样可能会发生:
...
public MyException(String message, int code, boolean report) {
this.message = message;
this.code = code;
this.report = report;
report();
}
...
int var = 0;
MyException ex = new MyException("test", 1, true);
if (var != 0) {
throw ex;
}
// Here the exception would be reported but never thrown.
这甚至可能吗?第三方图书馆可以这样做吗?任何帮助表示赞赏!
答案 0 :(得分:1)
Spring AspectJ如果已经有了弹簧,可能是答案-参见示例https://howtodoinjava.com/spring-aop/aspectj-afterthrowing-annotation-example/
答案 1 :(得分:1)
您可以使用和UncaughtExceptionHandler。
使用模式为:
UncaughtExceptionHandler
,这只是一种方法的实现:uncaughtException()
如果使用的是Java EE或Spring之类的任何框架,则可能会有更好(更简洁)的方法,例如Java EE ExceptionMapper。