Java throws: The Java throws keyword is used with the signature of the method to indicate that the method may raise an exception. The method that uses the Java throws keyword along with its signature is not responsible for handling the exception. It is the responsibility of the caller method to handle the exception that is thrown by the called method. Thus, Java throws keyword delegates the exception handling to the caller method.

Syntax:

The syntax of the Java throws keyword is mentioned below.

Java throws Keyword Examples

Let’s understand the usage of the throws keyword with the help of some examples.

Throwing Single Exception

FileName: ThrowsExample.java

Output:

Java throws

Explanation: In the above code, the main() method is responsible for the calling of the searchFile() method. Thus, it becomes the responsibility of the main() method to handle the IOException as the searchFile() method has used the throws keyword in its signature. If “throws IOException” is removed from the signature of the searchFile() method, then the method has to deal with the IOException raised; otherwise, the compiler will punish by giving a compilation error.

Throwing Multiple Exceptions

The throws keyword is also used to throw multiple exceptions. The following program illustrates the same.

FileName: ThrowsExample1.java

Output:

Java throws

Responsibility Delegation

In Java, it is possible to delegate the responsibility of handling the raised exception. Observe the following program.

FileName: ThrowExample2.java

Output:

Java throws

Explanation: The above code is the modified version of the previous one. In this code, the try-catch block that was handling the raised exceptions has been removed, and the main() method used the throws keyword in its signature. Thus, the main() method also delegated the responsibility of handling the raised exception. Since JVM (Java Virtual Machine) calls the main() method, the JVM handles the raised exceptions. If the throws keyword is removed from the signature of the main method, an error is occurred.

Important Points Regarding the Java throws Keyword

Following are some important points to remember regarding the Java throws keyword.

  • The Java throws keyword must be used for the checked exceptions. Using the throws keyword with the unchecked exceptions does not make any sense. Examples used in this tutorial contain only the checked exception.
  • It provides information to the compiler regarding exceptions. It never guarantees the normal termination of the program.
  • It provides exception-related information to the caller method.

Pin It on Pinterest

Share This