In Java, the throws keyword indicates that a method might throw one or more exceptions during its execution. It’s an important part of exception handling and is particularly relevant for checked exceptions, which are exceptions that the compiler forces you to handle or declare in your code.
Using the throws keyword, you declare the potential exceptions that a method may propagate to its caller, allowing the caller to handle them appropriately.
Syntax:
return_type method_name() throws exception_class_name {
}
Difference between throw and throws in Java
| SI.No | Throw | Throws |
|
1. |
Used to trigger an exception in a method
|
Used to describe the exception categories that a method can throw. |
|
2. |
No more than one exception may be raised | There could be a few exceptions declared. |
|
3. |
Syntax:
An object (new type) used inside the method comes after the throw.
|
Syntax:
A class is immediately after throws and when the method signature is used. |
Which exception should be declared:
Checked Exception only because:
- Unchecked exception: within our power to fix our code.
- Error: not within our power. For instance, nothing can be done if a VirtualMachineError or StackOverflowError happens.
Advantage:
- It is now possible to propagate (forward in the call stack) a checked exception.
- It informs the method’s caller with details on the exception.
Checked and Unchecked Exception:
Checked Exception:
They are checked at compile-time. For example, IOException, InterruptedException, etc..,
Unchecked Exception:
They are not checked at compile-time but at run-time. For example ArithmeticException, NullPointerException, ArrayIndexOfBoundException, exception under Error class, etc..,
1. Java throws an Example Program:
import java.io.*;
class Main {
public static void findFile() throws IOException {
File newFile=new File("test.txt");
FileInputStream stream=new FileInputStream(newFile);
}
public static void main(String[] args) {
try{
findFile();
} catch(IOException e){
System.out.println(e);
}
}
}
Output:
java.io.FileNotFoundException: test.txt (No such file or directory)
Explanation:
- When we run this program, if the file test.txt does not exist, FileInputStream throws a FileNotFoundException which extends the IOException class.
- If a method does not handle exceptions, the type of exceptions that may occur within it must be specified in the throws clause so that methods further up in the call stack can handle or specify them using the throws keyword themselves.
- The findFile() method specifies that an IOException can be thrown. The main() method calls this method and handles the exception if it is thrown.
Example 2: Java throw keyword
class Main {
public static void divideByZero() {
throw new ArithmeticException("Trying to divide by 0");
}
public static void main(String[] args) {
divideByZero();
}
}
Output:
Exception in thread “main” java.lang.ArithmeticException: Trying to divide by 0 at Main.divideByZero(Main.java:3)
at Main.main(Main.java:7)
Explanation:
- This code creates the Java class “Main.” These two approaches are used in this class:
- The method divideByZero() returns an ArithmeticException with the message “Trying to divide by 0.” In essence, it creates an error state that indicates a division by zero operation attempt.
- main(Args[] in a String): This is where the program begins. The divideByZero() function is invoked.
- In plainer language, the code shows how to produce and deal with an error scenario in Java deliberately. The main method calls the function that is defined to cause an arithmetic exception (division by zero). When the divideByZero() method is used, an exception is thrown that can, if necessary, be detected and handled elsewhere in the code.
Example 3: Throwing a Checked exception
import java.io.*;
class Main {
public static void findFile() throws IOException {
throw new IOException("File not found");
}
public static void main(String[] args) {
try {
findFile();
System.out.println("Rest of code in try block");
} catch (IOException e) {
System.out.println(e.getMessage());
}
}
}
Output:
File not found
Explanation:
- An IOException is produced due to the message we passed to the findFile() function’s constructor.
- The procedures that call this findFile() function must either handle this exception or explicitly specify it using the throws keyword.
- The main() procedure handled this exception. The try block gives way to the catch block when an exception is raised during program execution. As a result, the catch block’s statements are executed in place of the try block’s remaining code.
There are two cases specified in Java throws keyword:
Case 1: We have caught the exception, i.e. we have handled the exception using try/catch block.
Case 2: We have declared the exception, i.e. specified throws keyword with the method.
Case 1: Handle Exception Using try-catch block
In case we handle the exception, the code will be executed fine whether the exception occurs during the program or not.
import java.io.*;
class M{
void method()throws IOException{
throw new IOException("device error");
}
}
public class Testthrows2{
public static void main(String args[]){
try{
M m=new M();
m.method();
}catch(Exception e){System.out.println("exception handled");}
System.out.println("normal flow...");
}
}
Output:
exception handled
normal flow. . .
Explanation:
- The M class is known to contain the method with the name method. This method is intended to raise an IOException.
- An IOException with the message “device error” is explicitly thrown by the procedure using a throw statement. This imitates an I/O device problem.
- The Testthrows2 class has a defined main method that belongs to it.
- In the main method, the statement M m = new M() generates a new instance of the M class.
- Using m.method();, the M class’ method is invoked.
- A try-catch block is necessary to handle any faults this function may throw because it is designed to throw an IOException.
- When an exception occurs, the catch block is activated, and it outputs
Case 2: Declare Exception
- If the exception is declared, the function will run without a problem if it doesn’t happen.
- Throws does not handle exceptions; therefore, if we declare an exception and it arises, it will be thrown at runtime.
A. If an exception does not occur
import java.io.*;
class M{
void method()throws IOException{
System.out.println("device operation performed");
}
}
class Testthrows3{
public static void main(String args[])throws IOException{//declare exception
M m=new M();
m.method();
System.out.println("normal flow...");
}
}
Output:
device operation performed
normal flow…
Explanation:
- There are two classes in the program: M and Test Throws 3.
- A method called method exists in the M class and is declared to throw an IOException. Inside the technique:
- To simulate a device operation, use
- the statement System.out.println(“device operation performed”);
- The main method contained in the Testthrows3 class is defined.
- Within the primary method:
- An IOException is explicitly stated to be thrown by the main procedure. This declaration implies that an IOException might be thrown by the main method.
- Using M m = new M();, a new instance of the M class is generated.
- Using m.method();, the M class’ method is invoked. There is no try-catch block necessary here because the method method is declared to throw an IOException.
- Executing the statement System.out.println(“normal flow…”); prints
B. If Exception occurs:
import java.io.*;
class M{
void method()throws IOException{
throw new IOException("device error");
}
}
class Testthrows4{
public static void main(String args[])throws IOException{//declare exception
M m=new M();
m.method();
System.out.println("normal flow...");
}
}
Output:
Exception in thread “main” java.io.IOException: device error at M.method(Testthrows4.java:4)
at Testthrows4.main(Testthrows4.java:10)
Explanation:
- There are two classes in the program: M and Testthrows4.
- A method named method that is declared to throw an IOException is defined by the M class.
- A throw statement that tosses an IOException with the message “device error” is found inside the method function. This mimics the occurrence of a device problem.
- The main method, likewise defined to throw an IOException, is contained in the Testthrows4 class.
- Within the primary method:
- Using M m = new M();, a new instance of the M class is generated.
- Using m.method();, the M class’ method is invoked.
- The main method must handle or declare this exception because the procedure is declared to throw an IOException.
- It prints “normal flow…” to the console when the command System.out.println(“normal flow…”); is run.
Summary
The throws keyword aids in creating a clear understanding between methods and the callers of those methods on any potential exceptions that can arise. This makes Java programs’ handling of exceptions more streamlined, readable, and reliable.

