Don’t Forget Your Root (Cause)

August 30, 2006 – 00:32 | java

We all know that this is bad:

JAVA:
  1. try {
  2.   // ...
  3. } catch (DaoException e) {
  4.   // do nothing.
  5. }

But some of us (namely the dude who wrote the code that drove me crazy trying to troubleshoot today) apparently didn't know this was almost equally bad:

JAVA:
  1. try {
  2.   // 200 lines of code with many dao calls.
  3. } catch (DaoException e) {
  4.   throw new AppException(e.getMessage());
  5. }

What's wrong with that is there is no way to tell at exactly which point DaoException was thrown, since the original stack traces are lost. So, my fellow Java programmers, please, please always do:

JAVA:
  1. try {
  2.   // 200 lines of code with many dao calls.
  3. } catch (DaoException e) {
  4.   throw new AppException(e.getMessage(), e); // <--- always pass along the cause!
  5. }

The only time should you be using the message-only constructor is when AppException is the root cause itself.

Trackback from your site, or follow the comments in RSS.
  1. 2 Responses to “Don’t Forget Your Root (Cause)”

  2. What about doing?

    ...
    catch (DaoException e) {
    throw new AppException(e);
    }

    By lowell on Sep 6, 2006

  3. Sure, that is fine. Although I would always add some message that is sensible in the wrapping context.

    By Jing Xue on Sep 8, 2006

Post a Comment