Mar*_*ena 4 java aop aspectj exception aspect
我试图捕获在我的Java类中的main中抛出的异常.
我的主要代码:
public static void main(String[] args){
new something();
throw new RuntimeException();
}
Run Code Online (Sandbox Code Playgroud)
在我的方面,我已经创建了两个,after() returning: execution(* main(*)) { advice}并 after() throwing(Exception e): execution(* main(*)) { advice }找出是否在主要或不是抛出异常,以便在每个建议上做一些不同的事情.
请注意,在第二个内部,我在输出中打印e异常使用:
System.out.println("Threw an exception: " + e + "Joinpoint: " + thisJoinPoint.getSignature().toString());
Run Code Online (Sandbox Code Playgroud)
问题是,即使我在main中抛出一个异常,我可以从输出中看到匹配的切入点是第二个(输出:) Threw an exception: java.lang.RuntimeExceptionJoinpoint: void main(String[])
,我仍然在输出中得到这个错误:
Exception in thread "main" java.lang.RuntimeException
at main(C.java:24)
Run Code Online (Sandbox Code Playgroud)
所以,据我所知,我没有抓住异常,我刚刚发现在main中发生异常.
有没有办法可以在不必使用的情况下捕获此异常around()?
您无法通过after() throwing建议来抑制异常,您需要使用around()您怀疑的建议.
void around(): execution(* MainClass.main(*)) {
try {
proceed();
} catch (Exception e) {
//suppress
System.out.println("Suppressed an exception: "
+ e + "Joinpoint: " + thisJoinPoint.getSignature().toString());
}
}
Run Code Online (Sandbox Code Playgroud)
一个after() throwing建议是好当异常是在你感兴趣的某个点抛出运行额外的代码,但它不会从传播停止例外,除非你抛出另一个异常,从你的建议代码(包住抑制异常,如果你这样做):
after() throwing(Exception e): execution(* MainClass.main(*)) {
System.out.println("Threw an exception: " + e + "Joinpoint: "
+ thisJoinPoint.getSignature().toString());
throw new RuntimeException("Another exception", e);
}
Run Code Online (Sandbox Code Playgroud)
编辑:我如何效仿加入一个例子before(),after() returning,after() throwing并after()建议在around() advice跟进一个问题在我的答案评论.
void around(): execution(* MainClass.main(*)) {
try {
//before() code
System.out.println("Before main started.");
proceed();
//after() returning code
System.out.println("Main exited normally.");
} catch (Exception e) {
//after() throwing code suppressing exception unless you rethrow it
System.out.println("Suppressed an exception: " + e + "Joinpoint: "
+ thisJoinPoint.getSignature().toString());
} finally {
//after() code
System.out.println("After main executed.");
}
}
Run Code Online (Sandbox Code Playgroud)
运行主类时,这将输出以下行:
Before main started.
Main started.
Suppressed an exception: java.lang.RuntimeException: errorJoinpoint: void MainClass.main(String[])
After main executed
Run Code Online (Sandbox Code Playgroud)
请注意,部件的代码after() returning不会被执行,因为您的主类没有正常完成,因为它会抛出异常,就像after() returning在这种情况下不会运行正常的建议一样.
| 归档时间: |
|
| 查看次数: |
1548 次 |
| 最近记录: |