throw, throws and finally

throw, throws and finally

  • In Java, exception handling is done using five keywords,
    • try
    • catch
    • throw
    • throws
    • finally
  • Exception handling is done by transferring the execution of a program to an appropriate exception handler when exception occurs.
  • Try is used to protected a block of code in which exception may occur. 
  • This block of code is called protected region. 
  • A catch statement involves declaring the type of exception you are trying to catch. If an exception occurs in protected code, the catch block that follows the try is checked, if the type of exception that occured is listed in the catch block then the exception is handed over to the catch block which then handles it.


  • Example:

class Excp
{
  public static void main(String args[])
  {
    int a,b,c;
    try
    {
      a = 0;
      b = 10;
      c = b/a;
      System.out.println("This line will not be executed");
    }
    catch(ArithmeticException e)
    {
      System.out.println("Divided by zero");
    }
    System.out.println("After exception is handled");
  }
}


  • Note: While using multiple catch statements, it is important to remember that sub classes of class Exception inside catch must come before any of their super classes otherwise it will lead to compile time error. This is because in Java, if any code is unreachable, then it gives compile time error.
  • Example:

class Excep
{
  public static void main(String[] args)
  {
    try
    {
      int arr[]={1,2};
      arr[2]=3/0;
    }
    catch(Exception e)    //This block handles all Exception
    {
      System.out.println("Generic exception");
    }
    catch(ArrayIndexOutOfBoundsException e)    //This block is unreachable
    {
      System.out.println("array index out of bound exception");
    }
  }
}


  • Nested try statement
    • try statement can be nested inside another block of try. 
    • Example:

class Excep
{
  public static void main(String[] args)
  {
    try
    {
      int arr[]={5,0,1,2};
      try
      {
        int x = arr[3]/arr[1];
      }
      catch(ArithmeticException ae)
      {
        System.out.println("divide by zero");
      }
      arr[4]=3;
    }
    catch(ArrayIndexOutOfBoundsException e)
    {
      System.out.println("array index out of bound exception");
    }
  }
}


  • throw, throws and finally:
    • throw keyword is used to throw an exception explicitly. 
    • Only object of Throwable class or its sub classes can be thrown. 
    • Program execution stops on encountering throw statement, and the closest catch statement is checked for matching type of exception.
    • Syntax : throw ThrowableInstance


    • Creating Instance of Throwable class
    • There are two possible ways to create an instance of class Throwable,
      • 1. Using a parameter in catch block.
      • 2. Creating instance with new operator.
      • Example: new NullPointerException("test");
  • Example:

class Test
{
  static void avg()
  {
    try
    {
      throw new ArithmeticException("demo");
    }
    catch(ArithmeticException e)
    {
      System.out.println("Exception caught");
    }
 }

 public static void main(String args[])
 {
    avg();
 }
}


  • throws Keyword
    • Any method that is capable of causing exceptions must list all the exceptions possible during its execution, so that anyone calling that method gets a prior knowledge about which exceptions are to be handled. 
    • A method can do so by using the throws keyword.
    • Syntax:

type method_name(parameter_list) throws exception_list
{
  // definition of method
}

    • Example:

class Test
{
  static void check() throws ArithmeticException
  {
    System.out.println("Inside check function");
    throw new ArithmeticException("demo");
  }

  public static void main(String args[])
  {
    try
    {
      check();
    }
    catch(ArithmeticException e)
    {
      System.out.println("caught" + e);
    }
  }
}


  • The difference between throw and throws
    • throw keyword is used to throw an exception explicitly.
    • throws keyword is used to declare an exception possible during its execution.
    • throw keyword is followed by an instance of Throwable class or one of its sub-classes.
    • throws keyword is followed by one or more Exception class names separated by commas.
    • throw keyword is declared inside a method body.
    • throws keyword is used with method signature (method declaration).
    • We cannot throw multiple exceptions using throw keyword.
    • We can declare multiple exceptions (separated by commas) using throws keyword.
  • finally clause
    • A finally keyword is used to create a block of code that follows a try block. 
    • A finally block of code is always executed whether an exception has occurred or not. 
    • Using a finally block, it lets you run any cleanup type statements that you want to execute, no matter what happens in the protected code. 
    • A finally block appears at the end of catch block.
    • Example:

Class ExceptionTest
{
  public static void main(String[] args)
  {
    int a[] = new int[2];
    System.out.println("out of try");
    try
    {
      System.out.println("Access invalid element"+ a[3]);
    }
    finally
    {
      System.out.println("finally is always executed.");
    }
  }
}

Thanks a lot for query or your valuable suggestions related to the topic.

Previous Post Next Post

Contact Form