throw and throws in Java

throw
An application can explicitly throw exception using the throw keyword.We can use throw for explicitly throwing custom exceptions.

The syntax of java throw keyword is given below.
throw exception;
For example: throw new ArithmeticException(“Invalid Number”);

package com.blog;

public class ThrowExample {

public static void main(String[] args) {
try{
System.out.println(“Inside try”);
throw new NullPointerException(“just for this example”);
}catch(NullPointerException ex){
System.out.println(“Inside catch”);
System.out.println(ex);
}finally{
System.out.println(“Inside finally”);
}
}

}

Output
Inside try
Inside catch
java.lang.NullPointerException: just for this example
Inside finally

throws
Any method capable of causing exceptions must list all the exceptions possible during its execution, so that anyone calling that method gets a prior knowledge about which exceptions to handle. A method can do so by using the throws keyword.

A throws clause can be specified in the method signature.
… someMethod(…) throws ExceptionType1, ExceptionType2,…, ExceptionTypen { … }

Each ExceptionType declares an exception, normally only checked exceptions are declared. The compiler enforces that the checked exceptions thrown by a method are limited to those specified in its throws clause.

The throws clause can specify unchecked exceptions, but this is seldom done and the compiler does not verify them.

 package com.blog;public class ThrowsExample {

public void throwsMethod() throws ClassNotFoundException{
Class.forName(“com.blog.ThrowsExample”);
}

public static void main(String[] args) {
ThrowsExample throwsExample = new ThrowsExample();
try {
throwsExample.throwsMethod();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}

}

Now the million dollar question pops up: When to use try-catch and when to use throws?

Using try-catch we kind of consume the exception and handle it there itself , whereas by using throws we propagate the exception to the caller so that it can handle it in a meaningful way.

The thumb rule is : You should only catch exceptions that you can actually handle in a meaningful way otherwise use throws.

Let’s say I have a method which reads a file provided by the input(file path) and then inserts rows to the database. Now the caller of the api will pass on the file path. There is some probability of not finding the file in the mentioned path. In this case, it is better to use throws, so that caller can handle it properly. On receiving the thrown exception,the caller can again call this api with some other backup file path. The job of my api is just read the file and insert rows in the database. The api is not responsible for handling the scenario in case the file is not there.

Leave a Reply

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