Throws Keyword in Java | Throws Clause

In Java, sometimes a method may throw an exception in a program but cannot handle it due to not have an appropriate exception handling mechanism.

In such a case, the programmer has to throw that exception to the caller of the method using throws clause.

Throws clause consists of throws keyword followed by a comma-separated by the list of all exceptions thrown by that method.

Throws Keyword in Java


Throws keyword in Java is used in the method declaration. It provides information to the caller method about exceptions being thrown and the caller method has to take the responsibility of handling the exception. 

Throws keyword is used in case of checked exception only because if we are not handling runtime exceptions (unchecked exceptions), Java compiler does not give any error related to runtime exceptions. If an error occurs, we are unable to do anything.

When the code generates a checked exception inside a method but the method does not handle it, Java compiler detects it and informs us about it to handle that exception.


In this case, compulsorily, we must handle that checked exception otherwise we will get an error flagged by Java compiler.

To prevent this error flagged by the compiler, we need to handle exceptions using throw clause. There are two ways to handle the exception:
1. By using try-catch block
2. By using throws keyword

The general syntax of using throws statement with a method declaration is as follows:
Syntax:

access_specifier return_type method_name(parameter list) throws exception
{
  // body of the method.
}

Java throws keyword can be used to throw multiple exceptions thrown by a method at a time. Multiple exceptions thrown by a method can be declared by separating them in comma with the help of throws keyword. The general syntax is as follows:
Syntax:

access_specifier return_type method_name(parameter_list) throws exception1, exception2, . . . .  exceptionN
{
  // body of the method.
}

When throws keyword is used with a method declaration, the method calling a method with throws keyword must be enclosed within try-catch block.

Throws Exception Example Programs


Let’s take a simple example program to understand throws clause better, where there is an InterruptedException raised by sleep() method.


Program source code 1:

public class ThrowsTest1 
{
public static void main(String[] args)
{
 Thread.sleep(1000);
 System.out.println("Hello Java");
 }
}
Output:
       Exception in thread "main" java.lang.Error: Unresolved compilation problem: 
	Unhandled exception type InterruptedException

When you will execute the above program, you will get compile-time error because Java compiler expects from you to handle InterruptedException either using throws clause or try-catch block. But you did not handle it. So, compile-time error is displayed.

Let’s see how to handle InterruptedException generated by sleep() method using throws clause.

Program source code 2:

public class ThrowsTest1 
{
public static void main(String[] args) throws InterruptedException
{
 Thread.sleep(1000);
 System.out.println("Hello Java");
 }
}
Output:
      Hello Java

In the above program, we handled the InterruptedException generated by sleep() method using throws clause, and we got the output as “Hello Java”.

Let’s see another program based on the throws clause.

Program source code 3:

package throwsProgram;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class ThrowsTest2 
{
 private String firstName, lastName;
 void accept() throws IOException
 {
// Reading data from keyboard.
  InputStreamReader sr = new InputStreamReader(System.in);
  BufferedReader br = new BufferedReader(sr);
  
  System.out.println("Enter your first name");
  firstName = br.readLine();
  System.out.println("Enter your last name");
  lastName = br.readLine();
 }
 void display(){
   System.out.println("Full Name: " +firstName+ " " +lastName);
 }
public static void main(String[] args) throws IOException
{
 ThrowsTest2 obj = new ThrowsTest2();
  obj.accept();
  obj.display();
  }
}
Output:
       Enter your first name
       Sachin
       Enter your last name
       Tendulkar
       Full Name: Sachin Tendulkar

Explanation: 

1. InputStreamReader and BufferedReader classes are used to read data from the keyboard.
2. readLine() method is used to read a line of text. This method may throw IOException if an I/O error occurs.

Program source code 4:

package throwsProgram;
import java.io.IOException;

public class ThrowsTest3 
{
 static void display() throws IOException
 {
   System.out.println("Hello Java");
   throw new IOException();
 }
public static void main(String[] args) {
ThrowsTest3 obj = new ThrowsTest3();
 try {
   obj.display();
} 
catch (IOException e) {
 System.out.println("Caught an exception: \n" +e);	 
  }
 }
}
Output:
      Hello Java
      Caught an exception: 
      java.io.IOException

Explanation:

In the example program, dispaly() is a static method that generates an IOException and throws an exception from method prototypes. By throwing exception from method prototypes, we inform the java compiler that the caller of method handles the exception.

In try block of main() method, we called display() method that generates an exception and throws the exception. Therefore, catch block followed by try block is executed to handle exception and print the statement.

Final words
Throws keyword in Java language provides flexibility method for throwing an exception instead of handling it. It takes a list of objects of type Throwable class as an argument. It is applicable to a method when a method raises a certain type of exception.

Thanks for reading!!!