The throws keyword in Java is used in a method declaration to specify that the method may pass one or more exceptions to the calling method. In this chapter, we will learn how the throws keyword works, when it should be used, how it differs from the throw keyword, and how it helps in handling checked exceptions effectively in Java programs.
The throws keyword is a keyword that is used to declare possible exceptions that a method can generate and allow those exceptions to be handled by the method that invokes it rather than within the method itself.
The syntax of throws keyword for single exception is as follows:
The syntax of throws keyword for multiple exceptions is as follows:
Here are examples of the throws keyword for single and multiple exceptions.
The following example demonstrates the throws keyword with a single exception:
Output:
Exception caught: Not eligible to vote
The following example demonstrates the throws keyword with multiple exceptions:
Output:
File not found: test.txt (No such file or directory)
Rule: If we are calling a method that declares an exception, we must either catch or declare the exception.
The throws keyword is used when a method might cause a checked exception but does not handle it itself. It tells the caller that the method can throw an exception, so the caller can decide how to handle it.
It is commonly used in methods that work with files, databases, or network operations that helps to keep the code clean by passing the responsibility of handling exceptions to higher-level methods.
If we are calling a method that declares an exception, we must either catch the exception or declare it using the throws keyword.
There are two cases:
When we handle the exception, the program executes normally whether the exception occurs or not.
The following example demonstrates handling an exception using a try-catch block:
Output:
exception handled normal flow...
If we declare the exception and it does not occur, the program runs normally. If the exception occurs, it is thrown at runtime, because throws only declare the exception - it does not handle it.
A) Exception Does Not Occur
The following example demonstrates declaring an exception using the throws keyword when no exception occurs:
Output:
Device operation performed normal flow...
B) Exception Occurs
The following example demonstrates declaring an exception using the throws keyword when the exception occurs at runtime:
When we run the above code, we get the following exception
Exception in thread "main" java.io.IOException: device error at M.method(Main.java:4) at Main.main(Main.java:10)
We request you to subscribe our newsletter for upcoming updates.