throws keyword in java with examples

Learn about the throws keyword in Java with examples. In simple words, the throws keyword is used to declare the exception. It gives an indication to the developer about the exception that may occur. It is better for the developer to provide the exception handling code so that the normal flow of the program is maintained. There are two ways to handle the code:

a. Exception thrown is caught by the try/catch block.
b. By declaring an exception in the method signature i.e using the throws keyword.

What will happen if you do not handle the code? you will get the compilation error if the exception is checked exception.

Read Also: Difference between throw and throws in Java

Note: If you are calling the function(method) that declares an exception using throws keyword, then you must either caught or declare the exception.

Syntax of throws keyword

methodName(Arguments) throws Exception1,Exception2,Exception3...{
  //code
}

In the above syntax, we are using the throws keyword to declare multiple exceptions i.e Exception1, Exception2, and Exception3, etc.
Mostly, checked exceptions should be declared in the method signature. They can be propagated. It provides information about the exception to the caller of the function.

throws keyword examples

Example 1: using try/catch block

1. Below is an example of a throws keyword in Java. In this example, we are handling the IOException using the try/catch block in the main method.

import java.io.*;
public class ThrowsExampleOne {
    public static void main(String args[]) {
      try {
        fetchFile();
      }
      catch(IOException ex) {
        System.out.println(ex);
      }
    }
    // Below method throws IOException
    public static void fetchFile() throws IOException{
        //Below code can throw IOException
        File file = new File("abc.txt");
        FileInputStream stream = new FileInputStream(file);
    }
}


Output:
java.io.FileNotFoundException: abc.txt (No such file or directory)

Example 2: declaring throws keyword in the main method

2.1 In the below example, we are handling the exception by declaring throws keyword in the main method. Since exception does not occur, the code is executed fine.

import java.io.*;
public class ThrowsExampleTwo {
    public static void main(String args[]) throws IOException{
        fetchFile();
        System.out.println("Code will execute fine");
    }
    public static void fetchFile() throws IOException{
        System.out.println("This code is not throwing IOException");
    }
}


Output:
This code is not throwing IOException
Code will execute fine

2.2 In the below example, we are actually throwing the IOException while declaring the throws keyword in the main method. As a result, a runtime exception will be thrown since throws does not handle the exception.

import java.io.*;
public class ThrowsExampleThree {
    public static void main(String args[]) throws IOException{
        fetchFile();
        System.out.println("This line will not be printed");
    }
    // Below method throws IOException
    public static void fetchFile() throws IOException{
        //Below code is throwing IOException
        throw new IOException("Exception is thrown from fetchFile Method");
    }
}


Output:
Exception in thread "main" java.io.IOException: Exception is thrown from fetchFile Method
  at ThrowsExampleThree.fetchFile(ThrowsExampleThree.java:10)
  at ThrowsExampleThree.main(ThrowsExampleThree.java:4)

Example 3 Throwing multiple exceptions using throws keyword

In the below example, we are throwing multiple exceptions i.e NullPointerException, InvalidClassException, IOException in the fetchFile() method.

Note: We have not handled the NullPointerException in the code because it is an unchecked exception. It is not mandatory to specify it in the throws clause and handle it.


import java.io.*;
public class ThrowsExampleFour {
    public static void main(String args[]) {
        try {
            fetchFile();
        }
        catch(InvalidClassException ex1) {
            System.out.println(ex1.getMessage());
        }
        catch(IOException ex2) {
            System.out.println(ex2.getMessage());
        }
    }
    public static void fetchFile() throws NullPointerException, InvalidClassException,IOException {
     
     // code that can throw IOException
     
     // code that can throw NullPointerException
     
     // code that can throw InvalidClassException
    }
}

When to use throws keyword over try/catch/finally block

1. It is possible that there are several methods that can cause exceptions. Writing try... catch block for each method will be difficult as code becomes long and less-readable.

2. throws keyword can also be used when you have checked exception that you do not want to handle it in the current method.

That's all for today, please mention in the comments in case you have any questions related to throws keyword in Java with examples.

About The Author

Subham Mittal has worked in Oracle for 3 years.
Enjoyed this post? Never miss out on future posts by subscribing JavaHungry