EXCEPTION HANDLING IN JAVA


Exception Handling In JAVA | Core Java Tutorial | Minigranth

Exception Handling in Java : Introduction

  • We can define exception handling in java as techniques to handle and deal with the exception so to maintain normal flow of the program.
  • An exception is an aberrant condition (an event) that occurs in a program during runtime.
  • Exception breaks the normal flow of program and program abruptly stops executing if exceptions are not handled.
  • Actually a Java exception is an object which is thrown at runtime when an exception occurs in the code.
  • Hence, A basic example of exception can be, divide by zero. When any number is divide by zero an exception occurs. We will see how exception handling in java is done below.

Exception Handling In Java : Java Exception Hierarchy

  • All exception classes are subclass of ThrowableThrowable is further branched into two subclasses. One is Exception class and other is Error class.
  • Exception class is further branched into subclass called RuntimeException  which contains all the unchecked exceptions which are predefined.  Some of them are NullPointerException, ArithmeticException, ArrayIndexOutOfBoundsException  
  • Error class defines exceptions that cannot be caught under normal scenario. These cannot be resolved by exception handling technique. Some of them are StackOverflowError ,VirtualMachineError etc.

  • This image describes the flowchart of Java Exception Hierarchy in exception handling in java.
    Java Exception Hierarchy : Flowchart

Exception Handling In Java : Checked and Unchecked Exceptions

  1. Checked Exception
    • Checked exceptions in Java are the subclass of Throwable. These exceptions are checked at compile time.
    • These exception must be handled and they are specified using throws keyword if they are present in the code.
    • For example : InterruptedException, FileNotFoundException, IOException etc.

  2. Unchecked Exception
    • Unchecked exceptions in Java are the subclass of These exceptions are checked at run-time.
    • These exceptions occurs due to some illegal code.
    • For example : NullPointerException, ArithmeticException, ArrayIndexOutOfBoundsException etc.

Exception Handling In Java : How to do it?

  • Exception handling in java is quiet a daunting task. So, in order to deal with exceptions, five keywords can used for exception handling according to the need and logic. These are :
    1. try
    2. catch
    3. throw
    4. throws
    5. finally
  • We will discuss each of the keyword one by one but before that let us discuss what happen when there will occur an exception in Java.


  • Example


    Output

  • In the above output the line marked with red shows the exception statement.
  • When Java run-time finds out that there has been an attempt to divide by zero then it throws an exception which is an object of type ArithmeticException.
  • Hence when an exception is thrown the program abnormally terminates and the further statements are not executed.
  • That’s why we use exception handling in java to stop abnormal program termination and maintain the flow of program. Now let us discuss the above keywords.
    1. The "try" Keyword
      • try is a block which contains those lines of code which may throw an exception. So those lines of code which we want to observe for exceptions are kept in try.
      • Syntax

        try {

                    // statement which may throw an exception;

        }


      • When an exception occurs inside try block it is thrown implicitly and is caught by catch block.
      • try should always be immediately followed by catch or finally.
       
    2. The "catch" Keyword
      • catch is a block which catches the exceptions thrown by try It also contains exception handling statements that display information about the exception.
      • Syntax

        catch(Exception_type object) {

                    //exception handling statements;

        }


    3. The "finally" Keyword
      • finally block contains code that need to executed after try block even if no exception is thrown.
      • Finally block is always executed whether an exception is thrown or not.
      • Syntax

        finally {

                    // statement to be executed after try block;

        }


      • Before discussing two more keywords throws and throw, let us take an example where we will handle the exception which occurred when we tried to divide a number by 0(zero).


      • Example


        Output

    4. The "throw" Keyword
      • As we all know Java throws exceptions implicitly and handle them. But we can also throw an exception explicitly.
      • throw keyword is used to explicitly throw an exception. Since an exception is an object we throw an object of the exception class explicitly using throw.
      • Syntax

        throw new Exception_class;


        Example
        • Let us take an example to understand throw keyword .


        • Example


          Output
    5. The "throws" Keyword
      • throws keyword is used to declare or specify an exception that a method might throw. It is generally used with method declaration statement stating the types of exception the method might throw.
      • Using throws keyword we ensure that during calling of method if any listed exception occurs then it must be handled to maintain the normal flow of the program.
      • Throws keyword is used with checked exceptions only.
      • Syntax

        type method_name(parameters) throws list_of_exceptions;


        Example
      • If there are multiple exceptions to be listed then they are separated by comma(,).
      • Let us take an example to demonstrate the use of throws.


      • Example


        Output

      • In above output we have listed the exception that might be thrown, in the method declaration. But listing exception does not help.
      • Throws does not handle exceptions, hence we have to supply try/catch block in main() to handle exception.
      • We can also provide try/catch in show() and use throws in main().

Exception Handling In Java : Multiple Catch Blocks

  • In a situation where the program may throw more than one exception, each exception has to be handled. Here we can use multiple catch blocks to handle different exceptions.
  • In case of multiple catch blocks, when an exception is thrown , each catch block is checked, and the type of exception is matched.
  • In case a first match is found the particular exception is handled in the matched catch block.
  • Example

    Example


    Output

    Note : While handling exceptions using multiple catch block , the superclass type exceptions should come after subclass type exceptions else the subclass type catch block will never be reached.

    For example : Exception is a superclass of all the subclass exceptions , hence it should come after subclass type catch block.

    catch(Exception e){

                System.out.println(“Exception Caught”);

    }

    catch(NullPointerException e1){

                System.out.println(“Null Pointer Exception”);

    }

    • In above example since Exception type catch block comes before subclass so NullPointerException catch block will never be reached.
    • So the corrected format is :

    catch(NullPointerException e1){

                System.out.println(“Null Pointer Exception”);

    }

    catch(Exception e){

                System.out.println(“Exception Caught”);

    }

Exception Handling In Java : Nested Try Blocks

  • Try block within try block is called nested try block. When a try block code may throw an exception an also the part of that try block may cause another exception, we can use nested try blocks.
  • Example

    Example


    Output

Exception Handling In Java : Creating User-Defined Exception / Custom Exceptions

  • In Java apart from system defined exceptions, we can create our own exceptions and use them. Hence the exceptions created by user are called user-defined exceptions or custom exceptions.
  • To create your exception, you have to create your own exception class that will extend superclass Exception.
  • Then you can define your message by invoking any of the constructor of Exception class. Two constructor of Exception class are :
  • 1) Exception() ;     //  Exception with no description

    2) Exception(String param);    // Exception with description


  • Let us take an example of custom exception :


  • Example


    Output

Exception Handling In Java : Common Exception & Meaning

  • ArithmeticException : This exception is thrown when there is some arithmetic error like divide by 0.
  • NumberFormatException : This exception is thrown when there is an illegal conversion of String to numeric format.

For example : Converting “A” to numeric format will throw this exception.

  • NullPointerException : This exception is thrown when we try to use a reference variable which points to null.

For example : Suppose we have a String s = null and if we try to find its length using s.length() , this exception will be thrown.

  • ArrayIndexOutOfBoundsException : This exception is thrown when array index is out of bounds.
  • There are many more exceptions defined in java.lang but these are some common run-time exceptions.