×

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

Prime Points in Java

The points that divide an integer into two halves containing a prime number are known as prime points. Printing every prime point of a specific number is the task. Let's...

6 minutes read.

Misc Operators in Java

In this article, we are going to learn about the misc operators in Java. Misc operators are nothing but the miscellaneous operators. The java programming language supports some of the...

4 minutes read.

Java Generate Random String

Java Generate Random String In this tutorial, we will learn about to generate random string in Java. Random generation strings mean any string will be generated, which does not follow any...

7 minutes read.

java.lang.NumberFormatException for Input String

java.lang.NumberFormatException for Input String The exception java.lang.NumberFormatException for input string occurs when we try to convert a string into a number format. For example, if someone converts the string “Tutorial & Example”...

3 minutes read.

Java While Loop

A while loop is used to repeatedly execute a set of statements as long as its condition evaluates to true. This loop checks the condition before it starts the execution...

1 minute read.

Java Map Interface

A map is a collection that maps keys to values, with no duplicate keys allowed. The elements in a map are key/value pairs. HashMap: HashMap stores the keys in a...

3 minutes read.

Bucket Sort in Java

Bucket Sort in JavaBucket sort is also called bin sort. Bucket sort first puts the elements of the array or list into different buckets. The first bucket contains elements of the smallest value. The...

11 minutes read.

Three-way operator in Java

The ternary operator in Java is the only conditional operator that takes three operands. It's a popular one-line substitute for the if-then-else expression among Java programmers. If-else clauses can be...

3 minutes read.

Java Finally Keyword

The final block in Java is used to run essential code, such as connection closure, among other things. Whether an exception is resolved or not, the Java finally block has...

3 minutes read.

Java Math log10() Method

The log10() method of Math class returns the base 10 logarithmic value for the specified double argument. Syntax: public static double log10(double a) Parameters: The parameter ‘a’ represents a double value. Return Value: The log10() method...

2 minutes read.

Switch Case Program in Java

Switch Case Program in Java The switch case program in Java controls which code snippet gets executed on the basis of the value of the expression mentioned in the switch statement....

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

How to Run Applet Program in Java

An applet is a new type of program which is put in a webpage. By inserting applet into a webpage dynamic content can be created. Characteristics of an Applet The applet is...

11 minutes read.

Java Integer min() method

The min()  method of Integer class returns the smaller of two int values. It returns the same result as by calling Math.min.  Syntax public static int min(int a, int b) Parameters The parameters ‘a’...

2 minutes read.

If Condition in Lambda Expression Java

The new and significant lambda expression feature of Java was added in Java SE 8. It provides a clear and concise mechanism for describing a single-method interface using an expression....

4 minutes read.

How to Convert String to Integer in Java

How to convert String to int in Java You need to convert String into int if you want to perform a mathematical operation on string which contains digits. To do so,...

3 minutes read.

FizzBuzz Program in Java

FizzBuzz is a well-known children's game. This game helps children learn division. The FizzBuzz game is becoming a popular programming question, appearing frequently in Core Java interviews. This section will...

3 minutes read.

India Map Pattern in Java

India Map Pattern is the pattern we'll code now using Java, as demonstrated. We will use a star in Java to print our India map.The specialty is that we will only...

4 minutes read.

Java Viva Questions and Answers

Question: Explain Java programming language. Answer: It is a high-level programming language. This programming language is based on the principles of object-oriented programming. Large-scale applications can be developed by using this...

16 minutes read.

Set Value to Enum in Java

In this article, you will be acknowledged about Enum in java. Most importantly you will learn how to set value to Enum or how to practically customize a value to...

3 minutes read.