Checked Exceptions vs UnChecked Exceptions - Java

Here is it with the image of Exception class hierarchy - Exception Class Hierarchy[image courtesy: JavaTpoint].
There are 3 key class to remember - ThrowableException 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 Throwable class except RuntimeException and Error are 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/catch or throw the 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/catch block.
  • Example: IOExceptionSQLException etc
Unchecked Exception:
  • The classes that extend RuntimeException are 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,NullPointerExceptionArrayIndexOutOfBoundsException etc
  • 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 avoid NullPointerException by simply checking the references - if(object!=null) or using even better techniques
Error:
  • Error refers irrecoverable situation that are not being handled by try/catch
  • Example: OutOfMemoryErrorVirtualMachineErrorAssertionError etc.

Comments

Popular posts from this blog

EJB - Stateful vs Stateless

Inversion of Control vs Dependency Injection