Throwing Exceptions


We have seen till now how exceptions thrown by methods we invoke such as nextInt() can be caught. We shall now see how we ourselves can throw exceptions. An exception is thrown by specifying the throw keyword followed by an object reference.

Throw <object>;

Only objects that have been created from classes which have implemented the Throwable interface can be thrown. An object of an Exception can be created just like any other object of a class by using one of the four forms of the constructor, which every Exception type inherits from the Throwable class. We shall see two of them for now. One of these is the default constructor and the other is the parameterised constructor which accepts a String which acts as a description for the exception object we are creating. The following statement shows the use of these two forms of the constructor to create an Exception object.

Exception e = new Exception();
Exception e = new Exception ( “This is an Exception”);

The objects created above may be thrown by using the throw keyword.

throw e;

We can also combine the statement that creates the Exception and the statement which throws the Exception into a single statement.

throw new Exception();

The following program shows the use of the throw keyword.

public class ThrowException {

    public static void main(String args[]){
     try{
      throw new Exception();
     } catch(Exception e) {
      System.out.println(“Exception caught”);
     }
    }
}

The output of this program would be

Exception caught

Prev : Nested try catch blocks

Author: , 0000-00-00