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.
- Does this code compile?
- 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:
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".
Yep, the NPE is correct.
Post a Comment