×

Java throws

Java throws: The Java throws keyword is used with the signature of the method to indicate that the method may raise an exception. The method that uses the Java throws keyword along with its signature is not responsible for handling the exception. It is the responsibility of the caller method to handle the exception that is thrown by the called method. Thus, Java throws keyword delegates the exception handling to the caller method.

Syntax:

The syntax of the Java throws keyword is mentioned below.

 accessModifier returnType nameOfMethod() throws Exception1, Exception2 …
{
  // statements
} 

Java throws Keyword Examples

Let’s understand the usage of the throws keyword with the help of some examples.

Throwing Single Exception

FileName: ThrowsExample.java

 // import statement
import java.io.*;
public class ThrowExample
{
// the searchFile() method declares
// that it may throw the IOException
public void searchFile() throws IOException
{
// the statement may or may not produce IOException
File f = new File("file.txt");
FileInputStream str = new FileInputStream(f);
}
// main method
public static void main(String argvs[])
{
// Creating an object of the ThrowsExample class
ThrowsExample thObj = new ThrowsExample();
try
{
  // invoking the searchFile() method
  thObj.searchFile();
}
catch(IOException io)
{
  System.out.println(io);
}
System.out.println("Code after the try - catch block is executed.");
}
} 

Output:

Java throws

Explanation: In the above code, the main() method is responsible for the calling of the searchFile() method. Thus, it becomes the responsibility of the main() method to handle the IOException as the searchFile() method has used the throws keyword in its signature. If “throws IOException” is removed from the signature of the searchFile() method, then the method has to deal with the IOException raised; otherwise, the compiler will punish by giving a compilation error.

Throwing Multiple Exceptions

The throws keyword is also used to throw multiple exceptions. The following program illustrates the same.

FileName: ThrowsExample1.java

 // import statement
import java.io.*;
public class ThrowsExample1
{
// the m() method declares
// that it may throw the IOException or ClassNotFoundException
public void m() throws IOException, ClassNotFoundException
{
// the statement may or may not produce IOException
File f = new File("file.txt");
FileInputStream str = new FileInputStream(f);
// the statement may or may not produce ClassNotFoundException
Class.forName("Tutorial&Example");
}
// main method
public static void main(String argvs[])
{
// Creating an object of the ThrowsExample1 class
ThrowsExample1 thObj = new ThrowsExample1();
// handling multiple exceptions
try
{
  // invoking the m() method
  thObj.m();
}
catch(IOException io)
{
  System.out.println(io);
}
catch(ClassNotFoundException e)
{
System.out.println(e);
}
// display statement
System.out.println("Code after the try - catch block is executed.");
}
} 

Output:

Java throws

Responsibility Delegation

In Java, it is possible to delegate the responsibility of handling the raised exception. Observe the following program.

FileName: ThrowExample2.java

 // import statement
import java.io.*;
public class ThrowExample2
{
// the m() method declares
// that it may throw the IOException or ClassNotFoundException
public void m() throws IOException, ClassNotFoundException
{
// the statement may or may not produce IOException
File f = new File("file.txt");
FileInputStream str = new FileInputStream(f);
// the statement may or may not produce ClassNotFoundException
Class.forName("Tutorial&Example");
}
// main method
public static void main(String argvs[]) throws IOException, ClassNotFoundException
{
// Creating an object of the ThrowExample2 class
ThrowExample2 thObj = new ThrowExample2();
// invoking the m() method
thObj.m();
// display statement
System.out.println("Code after the try - catch block is executed.");
}
} 

Output:

Java throws

Explanation: The above code is the modified version of the previous one. In this code, the try-catch block that was handling the raised exceptions has been removed, and the main() method used the throws keyword in its signature. Thus, the main() method also delegated the responsibility of handling the raised exception. Since JVM (Java Virtual Machine) calls the main() method, the JVM handles the raised exceptions. If the throws keyword is removed from the signature of the main method, an error is occurred.

Important Points Regarding the Java throws Keyword

Following are some important points to remember regarding the Java throws keyword.

  • The Java throws keyword must be used for the checked exceptions. Using the throws keyword with the unchecked exceptions does not make any sense. Examples used in this tutorial contain only the checked exception.
  • It provides information to the compiler regarding exceptions. It never guarantees the normal termination of the program.
  • It provides exception-related information to the caller method.

Related Topics

How to Create a Generic List in Java?

Generics are types that have parameters. The goal is to make it possible for methods, classes, and interfaces to take type (Integer, String, etc., and user-defined types) as a parameter....

4 minutes read.

Difference Between BufferedReader and FileReader

BufferedReader: To read data from a specified character stream, two classes are used: buffered readers and file readers. Both of them have advantages and disadvantages. Although how they operate is the...

6 minutes read.

Binary Search Java

Binary search is a search mechanism for key elements from the given List/Array. In Binary search, the search mechanism is followed by dividing the array into parts; hence the search...

3 minutes read.

Pyramid Program in Java

Pyramid Program in Java In the previous section, we have discussed about the number pattern programs in Java. The logic for the number pattern and pyramid pattern is the same except...

2 minutes read.

Difference between print() and println() in Java

In this tutorial, we will discuss the differences between print and println in Java language. There are mainly two methods to display the text on the console printprintln The above two methods are...

4 minutes read.

Java Program to remove duplicate characters in a string

In strings, we can find many characters present one or more times in a string; accessing a particular character is difficult due to repetition. Duplicate characters will present in the...

5 minutes read.

Why String in Immutable in Java?

Why String in Immutable in Java Immutable means unchangeable or unmodifiable.  Strings in Java are immutable, it means once a string is created, it cannot be modified or changed. Any change...

2 minutes read.

Dangling Else problem in Java

A language interpretation uncertainty is the hanging other issue. The following two types of condition executed code are both possible in programming: 1. if-then-else form 2. if-then form When dealing with the nested...

3 minutes read.

Sort Dates in Java

The Collection class's sort() method, which is a component of the Comparator mechanism, arranges the data in decreasing order. The Comparator interface can be used to accomplish the goal while...

4 minutes read.

Java Math floor() Method

The floor() method of Math class returns the largest double value that is equal to a mathematical integer and is less than or equal to the argument. Syntax: public static double floor(double...

2 minutes read.

Java concurrency interview questions

During technical interviews, one of the most challenging and sophisticated subjects is concurrency in Java. This page offers responses to some of the related interview questions you might come across. 1....

11 minutes read.

Properties Class in Java

Properties class is associated with Java since JDK 1.0, i.e. it is a legacy class. It is the subclass of Hashtable. It is used to maintain the lists of values in which...

5 minutes read.

String isnullorempty in Java

What do you mean by String? Strings are a collection of characters that are commonly used in Java programming. Strings are regarded as objects in the Java programming language. “String” is a...

4 minutes read.

Knapsack problem in Java

We have a collection of items in the knapsack problem. Every object has a weight and a value. These things should go in a knapsack. But there is a weight...

3 minutes read.

Basic Terms in Multithreading

To understand the terms of multithreading, we must have knowledge about concurrency, processes, and threads. Concurrency The concurrency stands for performing multiple tasks at the same time. In the process communication, the operating system permits the process...

8 minutes read.

Fall through in Java

In this article, you will be acknowledged about the fall through condition in Java along with an example program. Fall through It is a situation where there isn't a break statement in...

3 minutes read.

How to Convert int to double in Java

How to Convert int to double in Java When two variables of different types are involved in the single expression, Java compiler uses built-in library function to convert the variable to...

2 minutes read.

Java BLOB

The two data types used in Java to store binary and big-character objects are BLOB and CLOB. In contrast to other types of data like float, int, double, etc., it...

4 minutes read.

How to Convert String to Object in Java

How to Convert String to Object in Java The Object is the super class of all classes. So you can assign a string to Object directly. There are two methods to...

3 minutes read.

Java Boolean toValue() Method

The valueOf() method of Java Boolean class returns a Boolean object representing the given Boolean or String value. It returns true, if the specified Boolean or string object is true...

2 minutes read.