r/ProgrammerTIL • u/iBzOtaku • 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.
11
u/seanprefect Feb 14 '18
There's good reason for that. Exceptions are the sorts of error you can safely catch and work with. There are other cases where that cannot be reasonably or safely done.
4
u/fakehalo Feb 14 '18
Never knew that one...almost seems like a design flaw to make something that appears to follow what other languages do, but not completely.
Was what was throwing the Throwable make sense to be a Throwable, or do you think it should have been an Exception?
57
u/nate-sonicbottle Feb 14 '18
Be advised: exceptions are problems that can be recovered from and essentially don't harm the long running operation of the application. e.g - FileNotFoundException - not finding a file doesn't always mean that the application has to terminate.
Errors are not recoverable problems and tend to me the application must terminate. e.g OutOfMemoryError - You have no more memory to make objects and you problem can't really recover from that.
You should never attempt to catch Errors. That being said I am surprised your container wasn't outputting the error in the tomcat logs.
5
u/metaconcept Feb 14 '18
Please never catch Throwable.
Java should never have allowed it. OutOfMemoryError is a subclass of Throwable (as well as a bunch of other nasty errors), and if your application throws that, I really, really want it to die so I can have it automatically restart.
1
u/HighRelevancy Feb 15 '18
why the christ
1
u/pangalgargblast Feb 14 '18
iiiinteresting. Thanks for posting this!
1
u/runneri Feb 14 '18
In c# there's the StackOverflow exception that is known as the uncatchable since it's a catastrophic error and can't be caught. What is the equivalent in Java?
1
u/snot3353 Feb 15 '18
I always like to point people towards diagrams like this when explaining exceptions:
https://stackoverflow.com/a/27763869
It's also really useful to understand the difference between checked (Exception) and unchecked (RuntimeException) and their subclasses.