Java throw Keyword With Examples

In the post try-catch block we have already seen some examples of exceptions but all those exceptions are thrown by Java run time. You may choose to throw an exception explicitly in your Java code, that can be done using throw statement in Java.

General form of Java throw statement

The throw statement requires a single argument; a throwable object.

throw throwableObj;

Here throwableObj must be an instance of Throwable class or any of its subclass.

How to get Throwable class instance

If you want to throw an exception explicitly you can get this Throwable class instance in two ways-

  1. You can create an instance using new operator. See example.
  2. You can use the exception parameter of the catch block and rethrow the exception. See example.

If there is a throw statement in a Java code then execution stops as soon as throw statement is encountered. Nearest catch block is checked for the matching exception type, if catch block has the matching exception type then that block handles the thrown exception. If matching exception type is not found then the next higher context is checked and so on.

Throw statement example with new exception instance

As stated above one of the way you can throw exception in your code is by creating an exception instance using new operator.

public class ThrowDemo {
  public static void main(String[] args) {
    try{
      if(args.length != 2){
        throw new IllegalArgumentException("Two parameters should be passed");
      }
    }catch(IllegalArgumentException exp){
      System.out.println("Exception in the code " + exp.getMessage());
      exp.printStackTrace();
    }
  }
}

Output

Exception in the code Two parameters should be passed
java.lang.IllegalArgumentException: Two parameters should be passed
at com.knpcode.ThrowDemo.main(ThrowDemo.java:8)

In the above code exception is thrown if 2 arguments are not passed. The constructor used while creating exception instance is the one that takes String argument. That way you can pass a clear reason why exception is thrown. There is a method getMessage() method in Exception classes that can be used to display that message.

Java throw statement example when same exception is rethrown

You can also rethrow the exception that is caught in a catch block. One of the common reason to do that is to see if there is any exception handler for that specific exception which is thrown. As example if you have a catch block with Exception as exception type it will catch most of the exceptions since Exception is higher up in the exception hierarchy . You can rethrow that exception to be caught by an exception handler with the specific exception type.

public class ExceptionDemo {
  public static void main(String[] args) {
    ExceptionDemo ed = new ExceptionDemo();
    try{
      ed.division(7, 0);
    }catch(ArithmeticException exp){
      System.out.println("Exception occurred while dividing" + exp.getMessage());
      exp.printStackTrace();
    }
  }
	
  private void division(int num1, int num2){
    double result;
    try{
      result = num1/num2;
      System.out.println("Result" + result);
    }catch(Exception exp){
      System.out.println("Exception occurred while dividing" + exp.getMessage());
      throw exp;
    }	
  }
}

Output

Exception occurred while dividing/ by zero
java.lang.ArithmeticException: / by zero
	at com.knpcode.ExceptionDemo.division(ExceptionDemo.java:18)
	at com.knpcode.ExceptionDemo.main(ExceptionDemo.java:8)
Exception occurred while dividing/ by zero
java.lang.ArithmeticException: / by zero
	at com.knpcode.ExceptionDemo.division(ExceptionDemo.java:18)
	at com.knpcode.ExceptionDemo.main(ExceptionDemo.java:8)

In the above code division method has a catch block with parameter of class Exception. From there you are rethrowing the caught exception. In the calling method it is caught again by the catch block which has parameter of type ArithmeticException.

Rethrowing a different exception

You can also catch one type of exception and rethrow exception of another type using Java throw keyword. Actually it is a best practice for exception handling to do that when you are propagating exception through separate layers. That helps in preserving loose coupling of your code.
As example– In your DB layer SQLException is caught there is no sense in letting the same exception propagate to your business layer. In this case best thing to do is catch the SQLException which is a checked exception in your DAO layer and rethrow another exception (unchecked) that should propagate to business layer. You should send the original exception instance as a parameter.

catch(SQLException ex){
  throw new RuntimeException("Error in DB layer", ex);
}

Related Posts

That’s all for the topic Java throw Keyword With Examples. If something is missing or you have something to share about the topic please write a comment.


You may also like

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.