What are the Runtime exceptions and what are Checked/Unchecked Exceptions and difference between Error/Exception.Why these many types? Instead Java may simply follow a simpl
Since I am a new Java developer, I have also faced some difficulties for distinguishing and dealing with different types of exceptions. That is why I have made a short note on this topic, and whenever I get confused I go through it. Here it is with the image of the Throwable
class hierarchy:
[image courtesy of JavaTpoint].
There are three key classes to remember here: Throwable
, Exception
and Error
. Among these classes Exception
can be divided into two types: "Checked Exception" and "Unchecked Exception".
Checked Exception:
Throwable
except RuntimeException
and Error
. try/catch
or indicate in the function signature that it throws
them and forcing us to deal with them in the caller.IOException
, SQLException
, etc.Unchecked Exception:
RuntimeException
are known as unchecked exceptions.ArithmeticException
,NullPointerException
, ArrayIndexOutOfBoundsException
, etc.ArithmeticException
, which can be avoided by a simple check on the divisor. Similarly we can avoid NullPointerException
by simply checking the references: if (object != null)
or even using better techniques.Error:
Error
refers to an irrecoverable situation that is not being handled by a try/catch
.OutOfMemoryError
, VirtualMachineError
, AssertionError
, etc.Why are these many types?
In addition to Stephen C's answer I want to say:
exception handling is a relatively expensive operation in Java. We should not put all exceptional situation in a try/catch
block. Excessive use of try/catch
s may hamper program performance.
In conclusion, Exception
s should be handled programmatically whenever possible. On the other hand, we cannot handle Error
s, so these might be some logical reasons why there are many types of exceptions.