Search code examples
exceptiontry-catchthrowable

What is the difference between handled and un-handled exceptions


I'd like to know the difference between handled and unhandeled Exceptions in Java. which one i should use a try/catch block and when I have to extend throwables.

also, if i extend throwables, do i always have to handle the exception in a separate class?

If exception is to be handled in a separate class, can i create custom functionality (e.g. Invoke another method or break a loop) instead of overriding the super constructor with just a custom message?


Solution

  • I presume by 'handled and unhandled' exceptions you mean 'checked and unchecked'.

    Unchecked exceptions - All classes which extend RuntimeException are called unchecked. They usually indicate programming bugs, such as logic errors or improper use of an API.

    Example of unchecked exceptions:

    ● ArithmeticException
    ● NullPointerException
    ● IndexOutOfBoundsException
    ● IllegalArgumentException
    ● ClassCastException
    

    For example if you try to access the 10th cell of an array with 5 cells only, it would cause an ArrayIndexOutOfBoundsException. This is a programmer bug and a programmer`s fault, so it should be treated as such. This exception should not be handled with try/catch, but instead should be checked with an if statement for the size of the array.

    Checked exceptions - These are exceptional conditions that a well-written application should anticipate and recover from. Checked exceptions in Java extend the Exception class but do not extend RuntimeException class. Checked exceptions are subject to the “Catch or Specify Requirement“:

    When in method's body some code may throws checked exception, the method must either handle this exception or specify that it may throws this exception

    Examples of checked exceptions:

    ● FileNotFoundException
    ● IOException
    ● SQLException
    

    For example you may have a perfectly well-written code that reads or writes data into a file, but the file may be suddenly deleted from the file system by another user. This is not a programmer`s error, but it CAN happen, so you MUST anticipate and handle this situation.

    So to summarize: Unchecked exceptions SHOULD NOT BE handled with try/catch - they should be treated as a bug and should be fixed (or avoided with if statements). Ofcourse you can use a try/catch block to handle a RuntimeException (for example NullPointerException), but it is NOT a good practice.

    Checked exceptions MUST BE either handled with try/catch blocks or when the method does not know how to handle them, they should be declared to be thrown by the method itself. Thus the responsibility for handling the exception is transferred to the methods that would invoke this very method. This is what the Catch or Specify requirement says.