Sunday, September 5, 2021

throw Statement in Java Exception Handling

It is possible for a Java program to throw an exception explicitly, that is done using the throw statement in Java.

The flow of execution, with in a method where throw is used, stops immediately after the throw statement; statements after the throw statement are not executed.

General form of throw in Java

General form of throw statement is-

throw throwableObject;
Here, throwableObject should be an object of type Throwable or any subclass of it.

We can get this throwableObject in 2 ways-

  • By using the Exception parameter of catch block.
  • Create a new one using the new operator.

Java example program using throw keyword

public class ThrowDemo {

 public static void main(String[] args) {
  ThrowDemo throwDemo = new ThrowDemo();
  try{
    throwDemo.displayValue();
  }catch(NullPointerException nExp){
     System.out.println("Exception caught in catch block of main");
     nExp.printStackTrace();;
  }
 }
 
 public void displayValue(){
  try{
    throw new NullPointerException();   
  }catch(NullPointerException nExp){
     System.out.println("Exception caught in catch block of displayValue");
     throw nExp;
  }
 }
}

Note that in this program throw keyword is used at two places. First time, in the try block of displayValue() method, it uses the new operator to create an instance of type throwable. Second time it uses the parameter of the catch block.

throw statement helps in preserving loose coupling

One of the best practices for the exception handling is to preserve loose coupling. According to that an implementation specific checked exception should not propagate to another layer.

As Example SQL exception from the DataAccessCode (DAO layer) should not propagate to the service (Business) layer. The general practice in that case is to convert database specific SQLException into an unchecked exception and throw it.

catch(SQLException ex){
    throw new RuntimeException("DB error", ex);
}

That's all for this topic throw Statement in Java Exception Handling. If you have any doubt or any suggestions to make please drop a comment. Thanks!


Related Topics

  1. Difference Between throw And throws in Java
  2. Exception Propagation in Java Exception Handling
  3. Try-With-Resources in Java With Examples
  4. Creating Custom Exception Class in Java
  5. Java Exception Handling Interview Questions And Answers

You may also like-

  1. Fail-Fast Vs Fail-Safe Iterator in Java
  2. How HashMap Works Internally in Java
  3. finalize() Method in Java
  4. Java Pass by Value or Pass by Reference
  5. Why Class Name And File Name Should be Same in Java
  6. Java CyclicBarrier With Examples
  7. Lambda Expressions in Java 8
  8. Count Number of Times Each Character Appears in a String Java Program

No comments:

Post a Comment