There are lots of debates about handling exception in Java, especially regarding checked vs unchecked exception and catching Throwable. I will not go into details, I think peoples more qualified than me already wrote entire chapters around this subject.
Anyway, a few weeks ago I had a huge debate with one of my colleagues about catching Throwable. He is really strong against catching Throwable and I agree with him … but with some exceptions. I totally agree, in a normal execution flow, you shouldn’t catch Throwable, and even if you catch it for any possible reason you have to throw it again.
Everything started around a watchdog thread which was responsible to monitor other threads and come to rescue when was need it. It doesn’t matter what the watchdog does, the question is : do you catch a Throwable in the main thread loop or do you let the thread to die? If you catch Throwable, what you gonna do with the exception?
Neither to say, my colleague was against catching Throwable or Error. He told me I have to let the thread die.
I was against this approach. I agree, some exceptions like OutOfMemory should be handled with an auto-restart.Also InterruptedException should be handled and you should stop the thread. And there are other exceptions which can need special handling. But I’m not sure it is better to stop the thread just because you got an Error.
Of course, you have a proof that something didn’t went well, but do you think the thread should die?
How about this scenario : your (watchdog) thread decides to connect to a FTP server to check some files and gets a LinkageError(NoClassDefFoundError for example because the FTP libraries couldn’t be found). Do you let the thread die just because this is an Error? Or you continue with the next operation and just log this failure?
I think there are situations when you cannot just let the thread die, you have to catch anything(Throwable) , eventually handle some particular exceptions, log the exception and continue. But maybe I’m wrong. I can accept I’m doing wrong things when I’m writing software, but right now I’m still convinced I did the right thing.
Any opinions?
Recent Comments