March 20, 2024

throw Vs throws in Java Exception Handling

In Java five keywords are used for exception handling namely – try, catch, finally, throw and throws. Out of these five, throw and throws keywords sound quite similar causing confusion thus the question what are the differences between throw and throws in Java exception handling.

Throw vs Throws in java

1- throws clause is used to declare an exception with in the method signature where as throw is used with in the code to actually throw an exception.

Exception declaration with in the method signature using throws
private void readFile() throws IOException {
  ....
  ....
}
Throwing exception using throw keyword
try{
  if(args.length != 2){
    throw new IllegalArgumentException("Two parameters should be passed");
  }
}

2- With throws clause multiple exceptions can be declared as a comma separated list. Where as throw can throw only a single instance of exception.

Declaring multiple exception with throws clause
private void readFile() throws FileNotFoundException, IOException, ArithmeticException {
  ....
  ....
}

3- With throws clause you can declare all the exceptions that may be thrown by your method code. You are not actually throwing an exception, just declaring them so the caller method can provide exception handling for the declared exceptions.

With throw you are actually throwing an exception that looks for the nearest catch block with the matching exception type.

4- With throws, while declaring exceptions you use the name of the exception classes itself.
With throw keyword you use an instance of the Throwable class or any of its sub-class, you don’t use the exception class itself.

With throws-
private void readFile() throws IOException
With throw
catch(IOException exp){   
 // throwing object of IOException class
 throw exp;
}
or you create an exception class object and throw it-
throw new IOException();
Class name (IOException) itself is given with the throws clause.

5- There is a restriction with throws clause that it has to be used with the method signature where as throw statement has to be part of the code where it may come anywhere inside the method, throw statement can be used with in a static block too.

Using throw with static block
static {
 try{
  ...
  ...
 }catch(Exception exp){
  System.out.println("Initialization error " + exp.getMessage());
  throw exp;
 }
}

That's all for the topic throw Vs throws in Java Exception Handling. If something is missing or you have something to share about the topic please write a comment.


You may also like

No comments:

Post a Comment