Exception Handling Example
3.2. Exception Handling Metrics and tracing are simple examples of building aspects. Another great simple example is to use AOP for exception handling. For example, SQLException is an exception that contains error information like invalid sql statement or deadlock that is similar per database vendor, but is expressed as different error codes and string messages. You can use AOP to intercept statement execution, catch SQLException errors, and turn them into typed exceptions that application code can handle independent of database vendor. So let's code an example of this. public class InvalidSQlException extends SQLException { InvalidSQLException(SQLException ex) { super(ex.getMessage(), ex.getSQLState(), ex.getErrorCode()); } } What we'll do is write an aspect that wraps calls to all java.sql.Statement execute methods and turn them into typed exceptions like the example above. We'll leave some code up to your imagination since such an aspect would be quite long to deal with every error code of every database vendor, but hopefully you can get the idea here. public class SQLExceptionAspect { public Object handleSqlException(Invocation invocation) throws Throwable { try { return invocation.invokeNext(); } catch (SQLException ex) { if (isVendorInvalidSqlErrorCode(ex.getErrorCode())) throw new InvalidSQLException(ex); if (isVendorDeadlockErrorCode(ex.getErrorCode()) throw new SQLDeadlockException(ex); ... and so on ... } } ... impl of isVendor methods ... } Now that the aspect is defined we use a call pointcut expression to intercept all the execute methods of java.sql.Statement.