Throws Keyword in Java
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 in Java 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 in Java:
- By using try-catch block
- By using throws keyword
Key Points of Throws Keyword
1. In Java exception handling, we use throws keyword to define a list of exceptions which may be thrown by that method.
2. We can use throws keyword in method or constructor declaration (signature) to denote exceptions that can be possibly thrown by that method.
3. Throws is followed by the exception class name.
4. With throws clause, we can declare more than one exception.
Syntax to Declare 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 a comma with the help of throws keyword.
The general syntax to throw multiple exceptions thrown by a method 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.
Example 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, a compile-time error is displayed.
Let’s write a code and understand how to handle InterruptedException generated by sleep() method using throws clause.
Example 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 have handled the InterruptedException generated by sleep() method using throws clause, and we got the output as “Hello Java”.
[adinserter block=”2″]
Let’s take another example program based on the throws clause in Java.
Example 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.
// Creating an object of InputStreamReader class.
InputStreamReader sr = new InputStreamReader(System.in);
// Creating an object of BufferedReader class.
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
In this example, we have used InputStreamReader and BufferedReader classes that mainly read data from the keyboard. The method readLine() is used to read a line of text. This method may throw IOException if an I/O error occurs.
Example 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
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.
Difference between Throw and Throws in Java
There are some key difference between throw and throws keyword in Java. They are as:
1. The keyword throw is used to throw an exception explicitly, while the throws clause is used to declare an exception.
2. Throw is followed by an instance variable, while throws is followed by the name of exception class.
3. We use throw keyword inside method body to call an exception, while the throws clause is used in method signature.
4. With throw keyword, we cannot throw more than one exception at a time, while we can declare multiple exceptions with throws.
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.
In this tutorial, you have learned about throws keyword in Java with the help of simple example programs. I hope that you will have understood the basic definition of throws keyword and practiced all example programs.
Thanks for reading!!!