r/ProgrammerTIL • • Feb 14 '18

Java [Java] TIL catch(Exception e) doesn't catch all possible errors.

tldr: Throwable catches errors that Exception misses

So I was trying to write a JavaMail web app and my app was not giving me any outputs. No error or success message on the web page, no errors in Tomcat logs, no email at the recipient address. I added a out.println() statement to the servlet code and manually moved it around the page to see how much of it was working. All my code was wrapped in:

try {} catch (Exception) {}

Realizing that my code was stopping midway through the try block and the catch block wasn't even triggering, I started googling and found this stackoverflow page. Turns out, Exception class is derived from the Throwable class. Changing my catch(Exception e) to catch(Throwable e) and recompiling the project worked. The webpage printed a stacktrace for the error and I was able to resolve it.

73 Upvotes

40 comments sorted by

View all comments

Show parent comment

1

u/fakehalo Feb 15 '18

I see, you're responding to my initial comment as I wasn't familiar with Throwables in general. Further on I realized OP was using catch(Throwable) to catch an Error, which I don't view as a design flaw anymore and is more up to the programmer if they want to delve into that realm (similar to the SIGSEGV signal handler route with C). I still don't get the analogies you were making, this is mostly confusion relating to my initial interpretation of what OP did at this point I think.