Differences between Exception and Error
I'm trying to learn more about basic Java and the different types of Throwables, can someone let me know the differences between Exceptions and Errors?
Solution 1:
Errors should not be caught or handled (except in the rarest of cases). Exceptions are the bread and butter of exception handling. The Javadoc explains it well:
An Error is a subclass of Throwable that indicates serious problems that a reasonable application should not try to catch. Most such errors are abnormal conditions.
Look at a few of the subclasses of Error
, taking some of their JavaDoc comments:
-
AnnotationFormatError
- Thrown when the annotation parser attempts to read an annotation from a class file and determines that the annotation is malformed. -
AssertionError
- Thrown to indicate that an assertion has failed. -
LinkageError
- Subclasses of LinkageError indicate that a class has some dependency on another class; however, the latter class has incompatibly changed after the compilation of the former class. -
VirtualMachineError
- Thrown to indicate that the Java Virtual Machine is broken or has run out of resources necessary for it to continue operating.
There are really three important subcategories of Throwable
:
-
Error
- Something severe enough has gone wrong the most applications should crash rather than try to handle the problem, - Unchecked Exception (aka
RuntimeException
) - Very often a programming error such as aNullPointerException
or an illegal argument. Applications can sometimes handle or recover from thisThrowable
category -- or at least catch it at the Thread'srun()
method, log the complaint, and continue running. - Checked Exception (aka Everything else) - Applications are expected to be able to catch and meaningfully do something with the rest, such as
FileNotFoundException
andTimeoutException
...
Solution 2:
This slide showing Java's exception hierarchy by @georgios-gousios concisely explains the differences between Errors and Exceptions in Java.
Solution 3:
Errors tend to signal the end of your application as you know it. It typically cannot be recovered from and should cause your VM to exit. Catching them should not be done except to possibly log or display and appropriate message before exiting.
Example: OutOfMemoryError - Not much you can do as your program can no longer run.
Exceptions are often recoverable and even when not, they generally just mean an attempted operation failed, but your program can still carry on.
Example: IllegalArgumentException - Passed invalid data to a method so that method call failed, but it does not affect future operations.
These are simplistic examples, and there is another wealth of information on just Exceptions alone.