Monday, June 11, 2007

Excellent advice on Java exceptions

Excellent advice on avoiding exception anti-patterns in Java from Tim McCune, Exception-Handling Antipatterns. Particularly noxious are the anti-patterns which swallow exceptions.

Quick trivial quiz.

  1. Does this code compile?
  2. If it compiles, what happens at runtime?
try {
    throw null;
} catch (final Throwable t) {
    System.out.println("t = " + t);
}

Before you chuckle too hard, recall that this is a perfectly valid C++ program, if contrived, and prints Something integral: 0:

#include <iostream>

int
main(const int argc, const char *argv[])
{
  try {
    throw 0;
  } catch (const int i) {
    std::cout << "Something integral: " << i << std::endl;
  } catch (...) {
    std::cout << "Something exceptional." << std::endl;
  }
}

UPDATE: I fixed the title.

2 comments:

Unknown said...

Just guessing here, but I would say it doesn't compile. Not sure whether the compiler would allow literal null as the object of a throw statement. OTOH, if it would allow you to throw a Throwable variable which referenced null, maybe this is OK too. If that's true, it'd either print "t = null", or the act of throwing null would raise NPE, thus causing "t = java.lang.NullPointerException".

Brian Oxley said...

Yep, the NPE is correct.