Throw and Throws keywords in Java With Examples

Java throw keyword

To explicitly throw an exception, we use the keyword throw. The keyword throw is followed by the instance of class Throwable or its child classes. Until now, we have witnessed situations where the exception occurred automatically. However, if we explicitly want to throw an exception as per our requirement, we use throw keyword. The throw keyword is used inside any method or block.

Syntax:

throw obj; //here obj can be instance of any checked/unchecked exceptions we discussed earlier.

 Example:

throw new ArrayIndexOutOfBoundsException(“Attempt to access invalid index”);

What happens after we encounter throw?

In case the statement with a throw is executed, the succeeding statements are skipped and it leaves the try block with an object of the class, we threw explicitly( in the above example it was ArrayIndexOutOfBoundsException). The rest of the process is similar to what happens to any exception which is thrown. It is tallied with the catch block(s), and the handler matching it gets executed i.e the statements enclosed within the matched catch block. Failure to find any takes it to the default handler as discussed earlier.

Example:

public class MyExceptionThrow{
  public static void main (String[]args)
  {
    try
    {
      throw new ArithmeticException("I am ArithmeticException thrown explicitly");
    }
    catch (ArithmeticException obj)
    {
      System.out.println ("You explicitly threw ArithmeticException inside main");
    }
  }
}

Output:

You explicitly threw ArithmeticException inside main

It must be noted that you cannot have multiple throw statement. The reason is simple. After encountering 1st throw statement, the succeeding throw statements become unreachable code resulting in a compile-time error.

public class MyExceptionThrow{
  public static void main (String[]args)
  {
    try
    {
      throw new ArithmeticException("I am ArithmeticException thrown explicitly");
      throw new ArrayIndexOutOfBoundsException("I am ArrayIndexOutOfBoundsException thrown explicitly");
    }
    catch (ArithmeticException obj)
    {
      System.out.println ("You explicitly threw ArithmeticException inside main");
    }
    catch (ArrayIndexOutOfBoundsException obj)
    {
      System.out.println ("You explicitly threw ArrayIndexOutOfBoundsException inside main");
    }
  }
}

Output:

MyExceptionThrow.java:7: error: unreachable statement
     throw new ArrayIndexOutOfBoundsException("I am ArrayIndexOutOfBoundsException thrown explicitly");
           ^
1 error

Java throws keyword

Till now we have seen that the exceptions are handled then and there inside the method. But it is possible to cascade the exception thrown without handling it there. All that needs to be done is to declare all the exceptions that the method might raise using the keyword throws. It makes the method calling it, liable to handle them.

Syntax:

<access specifier> <return-type> method_name(parameter-list) throws <One or more exceptions separated by comma>{
//Program statements
}

Example:

public void myMethod() throws ArithmeticException,ArrayIndexOutOfBoundsException{
//Code
}

It indicates that myMethod() can throw ArithmeticException and ArrayIndexOutOfBoundsException. So any method calling myMethod() needs to handle these exceptions using catch block.

Example:

public class MyExceptionThrows{
  public static void main (String[]args)
  {
    try{
        myMethod();
       }
    catch (ArithmeticException obj)
    {
      System.out.println ("You caught ArithmeticException inside main");
    }
  }

  public static void myMethod() throws ArithmeticException{
      throw new ArithmeticException("I am ArithmeticException thrown explicitly");
    }
}

Output:

You caught ArithmeticException inside main

 We can see that the main method is calling myMethod. As a result, the exception thrown is now to be taken care of by the main method.

Note that, if the main also dint care to handle the exception, it gets cascaded to the java default exception handler. It is not a good practice to keep any exception to be handled by the default-handler.

public class MyExceptionThrows{
  public static void main (String[]args){
        myMethod();
  }

  public static void myMethod() throws ArithmeticException{
      throw new ArithmeticException("I am ArithmeticException thrown explicitly");
    }
}

Output:

Exception in thread "main" java.lang.ArithmeticException: I am ArithmeticException thrown explicitly
        at MyExceptionThrows.myMethod(MyExceptionThrows.java:8)
        at MyExceptionThrows.main(MyExceptionThrows.java:4)     

The default handler will point out every exception in the same manner by displaying the details of the call stack. It won't handle it the way we expect. Hence in order to handle it suiting our purpose, we must always handle our exceptions.

This was an overview of Java throw and throws. We will discuss the finally keyword in the next lecture.