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
You may also like-
No comments:
Post a Comment