Throw statements

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

No comments:

Post a Comment