开发者

Catch a non-specific exception when the caller apply the same action for each exception handle

开发者 https://www.devze.com 2023-01-31 21:34 出处:网络
I have to dynamically instantiatecertain class based on runtime configuration. So, I need to invoke the method newInstance() and accordingly handle the exceptions:

I have to dynamically instantiate certain class based on runtime configuration. So, I need to invoke the method newInstance() and accordingly handle the exceptions:

try {
    clazz.newInstance();
} catch (InstantiationException ex) {
 开发者_JS百科   logger.error(ex, ex);
    throw new RuntimeException(ex);
} catch (IllegalAccessException e) {
    logger.error(ex, ex);
    throw new RuntimeException(ex);
}

In this point of my code the only way to handle this exceptions is by attempting to log the error and present a friendly message to the user (rethrowing the exception as runtime ,the view layer will catch the runtime exception)

<exception class="java.lang.Exception">
  <redirect view-id="/error.xhtml" />
</exception>

The point is that if I can't reasonable recover the error for any exception throw when method newInstance() is called and for each exception the same action is applied (log and rethrow the exception), is a better approach to replace the code above handling a non-specific exception like :

try {
    clazz.newInstance();
} catch (Exception ex) {
    logger.error(ex, ex);
    throw new RuntimeException(ex);
}


This is, unfortunately, a limitation of Java. I believe Java 7 may address this.

Until then, however, you are stuck with two unpalatable options:

  1. Catch each exception and cut-and-paste the behaviour.
  2. Catch Exception and write the behaviour once.

I personally prefer 1. They're both nasty, but at least with 1 you won't get weird stuff happening when you get SomeCrazyException being thrown somewhere down the line.


I found this nice article about generic-exceptions Beware the dangers of generic Exceptions. The author explain several reasons in order to avoid handle generic-exception (with a few exceptions) . Generally speaking in my opinion these are the relevant points :

  • A generic catch (Exception e) catches all subclasses of RuntimeException. And according that runtime exceptions indicate programming erros AND is not expected to recover those errors.

  • If your code just catches Exception , you'll probably never know if the method you are calling later adds a new checked exception to its method signature.

  • The caller may be able to recover from some errors but not from others.

  • Logging is limited because only one catch clause doesn't know the specific exception being caught.

0

精彩评论

暂无评论...
验证码 换一张
取 消