Eri*_*ric 5 aop aspectj exception-handling
我正在使用aspectJ写一个非弹簧aop方面,我正在写一个之前的建议.
在我以前的建议中,假设我想打开一个文件.所以我这样执行它:
public before(): mypointcut() {
File file = new File("myfile");
file.getCanonicalPath();
}
Run Code Online (Sandbox Code Playgroud)
但IntelliJ抱怨IOException是一个未处理的异常.如何编写之前的建议,以便它可以捕获并重新抛出异常或允许未处理的异常?
为了将异常传递到调用堆栈,您必须在建议中添加一个 throws 声明,就像正常的方法调用一样:
public before() throws IOException: mypointcut() {...}
Run Code Online (Sandbox Code Playgroud)
此建议只能应用于声明本身抛出此异常(或异常的父异常)的方法。
为了重新抛出它,您需要捕获异常并在 RuntimeException 实例中重新抛出它,如下所示:
public before(): mypointcut() {
File file = new File("myfile");
try {
file.getCanonicalPath();
} catch (IOException ex) {
throw new RuntimeException(e);
}
}
Run Code Online (Sandbox Code Playgroud)
如果这是个好主意那就是另一个故事了......
| 归档时间: |
|
| 查看次数: |
3057 次 |
| 最近记录: |