×

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

Replace character in string Java

Characters in Java In the package of Java language, there is a container class called Character. A single field of type char is contained in a Character object. For manipulating characters,...

4 minutes read.

Polymorphism Program in Java

Polymorphism Program in Java: Polymorphism means the existence of different forms of an object. The object can be a class object or a real-time entity. For example, a person can...

5 minutes read.

Java exception list

Java uses exceptions, like the majority of contemporary programming languages, to deal with both errors and "extraordinary events." When an exception arises inside the program, it messes up the regular...

6 minutes read.

Dutch National Flag Problem in Java

Dutch National Flag (DNF) is a programming issue that Edsger Dijkstra put up. The white, red, and blue hues make up the Dutch flag. The goal is to haphazardly set...

6 minutes read.

Traverse through HashMap in Java

In this tutorial, we will discuss traversing through HashMap in Java Introduction: HashMap<Key, Value> is a part of the java collection implemented from the java 1.2 version. HashMap is written as HashMap<K,...

4 minutes read.

How to uninstall the Java in Ubuntu

We need java on our computers in our daily lives because there are lots of different applications that are developed using the java environment, so we have to install java...

4 minutes read.

Minimum Difference Between Groups of Size Two in Java

There is given an array with various integers in it. The goal is to divide the elements into distinct groups, each of which has just two, so that the difference...

3 minutes read.

Java Architecture

Java architecture is a combination of three parts they are JVM, JRE and JDK. These components will help in the functioning of the java programs. The process of code interpretation...

6 minutes read.

InputMismatchException in Java

What is InputMismatchException? One of the most frequent errors in Java is the InputMismatchException. Because the InputMismatchException is a subtype of the java.lang, it is an unchecked exception. RuntimeException.Because it is...

4 minutes read.

Deadlock Prevention and avoidance in Java

This tutorial will discuss deadlock prevention and Avoidance in Java programming language. Introduction Multithreading in Java includes deadlock. We can multitask by running several threads concurrently in the multithreading environment. Deadlock occurs...

4 minutes read.

Java HashSet

HashSet implements the set interface. It uses the hash table to make the collection to store different data types. The hash set is the unordered collection of different data types....

6 minutes read.

Enum Java Interview Questions

1. What exactly is Java? Java is a portable, high-level, object-oriented, robust, secure, platform-independent, multi-threaded, high-performance programming language. Developed in June 1991 by James Gosling, also known as Platform. 2. Enum is...

3 minutes read.

How to add Elements in Array in Java

Consider an array of the size n, in the given size we must add the elements in the given array. In this tutorial we are preferred to learn how to add...

3 minutes read.

Difference between Abstract Class and Interface

There is a similarity between abstract class and interface is that we cannot create objects for both of them. But irrespective of this, there are some differences between them, let’s...

2 minutes read.

Factorial Program in Java using Recursion

Factorial Program in Java Factorials are used in mathematics to calculate permutations and combinations. It is denoted by the exclamatory symbol (!). Suppose, p is a number whose factorial is to...

3 minutes read.

Convert JSON to Map in Java

JACKSON and GSON libraries are two extremely capable JSON-related libraries offered by Java. To efficiently work with the returned JSON data, we frequently need to convert JSON responses into a...

6 minutes read.

JAR File in Java

What is a JAR File? JAR stands for Java Archive. It is a file format mainly used to combine many Java class files and the corresponding metadata and resources into one...

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.

Inheritance Program in Java

Inheritance Program in Java Inheritance is one of the important pillars of Object-Oriented Programming that facilitates parent-child relationships in programming. Using inheritance, we can create a new class with the help...

7 minutes read.

Package Program in Java

Package Program in Java The package program in Java helps us to understand the significance of packages in Java. Packages are mainly used to group together similar classes, interfaces and sub-packages....

6 minutes read.