throw Keyword

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 get an instance of class Throwable,

  1. Using a parameter in catch block.
  2. Creating instance with new operator.
    new NullPointerException("test");
    

    This constructs an instance of NullPointerException with name test.


Example demonstrating throw Keyword

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(); 
 }
}

In the above example the avg() method throw an instance of ArithmeticException, which is successfully handled using the catch statement.


throws Keyword

Any method 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 to handle. A method can do so by using the throws keyword.

Syntax :

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

NOTE : It is necessary for all exceptions, except the exceptions of type Error and RuntimeException, or any of their subclass.


Example demonstrating throws Keyword

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);
  }
 }
}

finally clause

A finally keyword is used to create a block of code that follows a try block. A finally block of code always executes whether or not exception has occurred. Using a finally block, 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.

finally clause in exception handling in java

Example demonstrating finally Clause

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]);
   /* the above statement will throw ArrayIndexOutOfBoundException */
  }
  finally 
  {
   System.out.println("finally is always executed.");
  }
 }
}

Output :

Out of try
finally is always executed. 
Exception in thread main java. Lang. exception array Index out of bound exception.  

You can see in above example even if exception is thrown by the program, which is not handled by catch block, still finally block will get executed.


Quantitative Aptitude
Reasoning
Programming
Interview