最爱Java

书山有路勤为径,学海无涯苦作舟

《AspectJ Cookbook》读书笔记五: 捕获异常处理上的连接点

    在Java中抛出异常时,会将其向上传递给调用者,直到它被作为try/catch块一部分的catch语句处理或者到达Java运行库并在控制台引发一条混乱的消息。如果捕获到异常,就应该将异常作为一个对象传递给catch块做合适的处理。同时,还有一种可能需要方面作为横切行为做一部分事情,或者替代catch块的正常行为。
一. 捕获何时捕捉异常
    使用handler(TypePattern)切入点。其语法如下:
    pointcut <pointcut name>(<any values to be picked up>) : handler(<class>):
 
   handler(TypePattern)切入点具有5个关键特征:
   1. handler(TypePattern)在捕获异常的作用域内选择连接点。
   2. handler(TypePattern)切入点的通知仅用于类型模式指定Throwable或其子类的地方。
   3. TypePattern声明无论何时捕捉到异常或其子类的匹配模式,都会应用相应的通知。
   4. handler(TypePattern)切入点只支持before()形式的通知。这意味着不能使用像around()这样的通知来重写catch块的正常行为。
   5. TypePattern可以包含通配符,用于选择不同类上的一系列连接点。
带有通配符的TypePattern 描述
mypackage..* 捕获mypackage包及其子包中的连接点类
MyClass+ 捕获MyClass类及其任何子类中的连接点

    下面的例子展示了捕获任何类抛出MyException类异常:

package com.aspectj;

public aspect HandlerRecipe {
    
/**
     * Specifies calling advice when any exception object
     * is caught that matches the following rules for its 
     * type pattern;
     * 
     * Type:MyException
     
*/

    pointcut myExceptionHandlerPointcut() : handler(MyException);
    
    
//Advice declaration
    before() : myExceptionHandlerPointcut() {
        System.out.println(
"------------------- Aspect Advice Logic -------------------");
        System.out.println(
"In the advice picked by " + "myExceptionHandlerPointcut()");
        System.out.println(
"Signature: " + thisJoinPoint.getStaticPart().getSignature());
        System.out.println(
"Source Line: " + thisJoinPoint.getStaticPart().getSourceLocation());
        System.out.println(
"------------------------------------------");
    }

}


二. 捕获抛出的异常
    结合使用args([Types | Identifiers])切入点 与handler(TypePattern)切入点,将捕获的异常展示为切入点上的标识符,可将其传递给相应的通知。
package com.aspectj;

public aspect AccessThrownException {
    pointcut myExceptionHandlerPointout(MyException exception) : handler(MyException) 
&& args(exception);
    
    
//Advice declaration
    before(MyException exception) : myExceptionHandlerPointout(exception) {
        System.out.println(
"------------------- Aspect Advice Logic -------------------");
        System.out.println(
"In the advice picked by " + "myExceptionHandlerPointcut()");
        System.out.println(
"Signature: " + thisJoinPoint.getStaticPart().getSignature());
        System.out.println(
"Source Line: " + thisJoinPoint.getStaticPart().getSourceLocation());
        System.out.println(
"Exception caught:");
        exception.printStackTrace();
        System.out.println(
"------------------------------------------");
    }

}
   

posted on 2008-07-11 09:28 Brian 阅读(1597) 评论(1)  编辑  收藏 所属分类: 《AspectJ Cookbook》读书笔记

评论

# re: 《AspectJ Cookbook》读书笔记五: 捕获异常处理上的连接点 2008-07-12 10:54 大梅沙云顶天海会所

nnn
  回复  更多评论   


只有注册用户登录后才能发表评论。


网站导航:
 

公告


导航

<2008年7月>
293012345
6789101112
13141516171819
20212223242526
272829303112
3456789

统计

常用链接

留言簿(4)

随笔分类

随笔档案

收藏夹

搜索

最新评论

阅读排行榜

评论排行榜