【发布时间】:2020-08-06 08:17:25
【问题描述】:
每次抛出某个自定义异常时,我都需要执行一个方法。执行的代码将向我的 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.
这甚至可能吗?第三方图书馆可以做到这一点吗?任何帮助表示赞赏!
【问题讨论】: