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.

Post a Comment