Checked Exceptions vs UnChecked Exceptions - Java
There are 3 key class to remember -
Throwable, Exception and Error in this hierarchy. Among these classes exception can be divided into two types - "Checked Exception" and "Unchecked Exception"
Checked Exception:
- The classes that extend
Throwableclass exceptRuntimeExceptionandErrorare known as checked exceptions. - Also known as compile time exception because these type of exceptions are checked at compile time. That means if we ignore these exception (not handled with
try/catchorthrowthe exception) then a compilation error occurred. - They are programmatically recoverable problems which are caused by unexpected conditions outside control of code (e.g. database down, file I/O error, wrong input, etc)
- We can avoid them using
try/catchblock. - Example:
IOException,SQLExceptionetc
Unchecked Exception:
- The classes that extend
RuntimeExceptionare known as unchecked exceptions - Unchecked exceptions are not checked at compile-time rather they are checked at runtime.And thats why they are also called "Runtime Exception"
- They are also programmatically recoverable problems but unlike checked exception they are caused by faults in code flow or configuration.
- Example:
ArithmeticException,NullPointerException,ArrayIndexOutOfBoundsExceptionetc - Since they are programming error, they can be avoided by nicely/wisely coding. For example "dividing by zero" occurs
ArithmeticEceeption. We can avoid them by a simple if condition -if(divisor!=0). Similarly we can avoidNullPointerExceptionby simply checking the references -if(object!=null)or using even better techniques
Error:
Errorrefers irrecoverable situation that are not being handled by try/catch- Example:
OutOfMemoryError,VirtualMachineError,AssertionErroretc.
Comments
Post a Comment