Throws keyword in java


Throws
keyword in Java is used to declare that a method may throw one or more exceptions. The caller of this method has to catch these exceptions. The catching of these exceptions is optional if the exceptions are of type unchecked exceptions or error. If the exceptions are not caught, a compile time error will be thrown.

throws keyword is used to handle Checked Exceptions. The throws clause lists the types of exceptions that a method might throw.

When to use throws keyword ?

When you don’t want to handle the exceptions in the method using try-catch block and want the exception to be handled by calling method, then declare the exceptions using the throws keyword in method signature.

Example of throws keword:

Let’s create a ThrowsDemo.java class. In this class display method throws 2 Checked exceptions IOException and ClassNotFoundException. Hence we have declared these exceptions in the method signature of display() method using the throws keyword.

Let’s run this demo class and check the output.

Output:

If you observe the output, the display method in the program has thrown a ClassNotFoundException. Since we have handled it in the main method the program executed successfully. If we wouldn’t have declared exceptions in the throws clause, the program would have thrown compile time error.

Want to know about throw keyword, then read this tutorial on Throw keyword in Java.

Related posts

Leave a Comment