×

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

Jdoodle Java

Everything is instantaneous and fast-paced in the modern world. Online compilers available via the internet are immensely helpful for programmers seeking to learn a new programming language but lacking the...

4 minutes read.

Java vs Go

Java: Java is an object oriented programming language. It is also known as multi threaded language. It was designed by James gosling in the year 1995. We can also say that...

4 minutes read.

Java Math cos() Method

The cos() method of Math class returns the trigonometric cosine of the specified angle. Syntax: public static double cos(double a) Parameters: The parameter ‘a’ represents an angle measured in radians. Return Value: The cos() method returns...

1 minute read.

Minimum Window Subsequence in Java

In this article, you will be very well acknowledged about the minimum window subsequence, what is the approach and how it is implemented. The example program is also executed and...

4 minutes read.

Java 8 Multimap

Java comes with several practical built-in collection libraries. However, there are situations when we need specialized collections that are not included in the Java standard library. The Multimap is one...

7 minutes read.

Convert JSON File to String in Java

Before understanding the conversion of JSON file to string, one must know about JSON. What is JSON? JSON stands for JavaScript Object Notation. It is an open standard format lightweight, text-based, and...

3 minutes read.

Java String equalsIgnoreCase() method

equalsIgnoreCase() method compares two Strings based on the their content but ignore the case. Syntax public boolean equalsIgnoreCase(Objects anObject) Parameter anObject: Object to be compared with the current String without case consideration. Returns It returns true...

1 minute read.

Java Identifiers

In Java, the symbolic notations used for identification are called identifiers. Identifiers can be the name for the class, variable name declaration, name of the package, constant name and many...

3 minutes read.

Dining Philosophers problem in Java

The Problem of the Dining Philosophers illustrates a concurrency issue involving the distribution of scarce resources among conflicting processes. Problem Statement Imagine a dining table with a circle in the middle and five...

3 minutes read.

Moran Numbers in Java

In this article, we will be acknowledged about the moran numbers in Java, how they are formed, what are the approaches to achieve the moran numbers. Moran Number A moran numbers are...

3 minutes read.

Structure of Java Program

Java is well-known as an object-oriented, secure, and platform-independent programming language. The Java programming language allows us to construct a wide variety of programs. Therefore, it is essential to fully...

6 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.

Int vs Integer in Java

In Java, numerical data can be stored using int or Integer. int and Integer both have different definitions but similar usage in Java. What is int in Java? int is a primitive...

4 minutes read.

Java Thread Priority in Multithreading

As we realise, java, being object-situated, works inside a multithreading climate in which the string scheduler relegates the processor to a string in light of the need for a string....

6 minutes read.

Java Framework List

The framework is the programs which are written in Java. Frameworks in Java are used to create web applications. The code which can reuse can act as a reference for...

6 minutes read.

Menu Driven Program in Java

Menu Driven Program in Java The menu-driven program in Java is a program that displays a menu and then takes input from the user to choose an option from the displayed...

3 minutes read.

Unicode System in Java

In this tutorial, we will understand the meaning and emergence of the Unicode system in java. The Unicode system is one of the important and useful features in the world...

6 minutes read.

History and Evolution of Java

Java is invented by James Gosling, Patrick Naughton, Chris Warth, Ed Frank, and Mike Sheridan at Sun Microsystems, Inc. in 1991. Java is related to C++, which is inherited from...

3 minutes read.

Sliding Window Problem in Java

A sliding window is used in computer science and data science to process large datasets. It involves breaking the dataset into smaller chunks or windows and then processing it in...

6 minutes read.

Get year from date in Java

The getYear() method of the Java date class returns a number calculated by deducting 1900 from the year that contains or starts with the instant in time represented by this...

4 minutes read.