In Java, throwing an exception is a standard mechanism to prevent the abnormal termination of the program due to unexpected errors. For this, the “throw” statement is used and an object of the specified Exception class is created. You can specify any message within the constructor as shown in the below syntax:
throw new ExceptionClass ("Exception Message");
Learn more: Java Exceptions Tutorial
This article provides a practical demonstration of throwing an exception in Java.
How to Throw Java Exceptions?
In the given example, the try-catch block handles the exceptions that may occur and disrupts the normal flow of the code. The throw statement displays the user-defined message for the given exception.
Within the try block, the exception is thrown with the custom message.The “new” keyword creates a new “Exception” that displays the given custom message. Within the catch block, the thrown exception will be caught and printed by the “e” instance of the Exception class:
try
{
throw new Exception("Basic Usage of Exception");
}
catch(Exception e )
{
System.out.println(e);
}
Complete Code & Output
Example 1: How to Throw a Checked Exception in Java?
The Checked Exceptions are determined by the compiler at the compilation time. In the following code, the Java compiler handles and throws the checked exceptions.
The following import statements include the necessary dependencies and classes from the java.util and java.io packages:
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
In this code snippet, the File class object “myObj” is created and initialized with the file’s path in the constructor. Replace the placeholder “<FilePath>” with the file’s path to be read. The Scanner object “myReader” is initialized with the file’s object for reading. The if-statement gets executed only when the length of the file is 0 and the exception is thrown. The throw statement throws a new “FileNotFoundException” with the human-readable error message shown in the code below. The catch block catches and prints the thrown exception:
try {
File myObj = new File(<FilePath>);
Scanner myReader = new Scanner(myObj);
if(myObj.length() == 0)
{
throw new FileNotFoundException("File cannot be read");
}
} catch (FileNotFoundException e) {
System.out.println(e);
}
Note: The File Path provided must contain double slashes as the single slash is used for special characters in Java e.g., “C:\\Users\\FileName”.
Complete Code & Output
Example 2: How to Throw an Unchecked Exception In Java?
Unchecked exceptions are the exceptions that occur when the program is running. Such exceptions are usually unrecoverable and often refer to system faults. The unchecked exceptions are thrown using the throw keyword as shown in the example given below:
Inside the try block, two integer variables are initialized. The if-statement determines the denominator’s value. The if-statement throws an Arithmetic exception with a custom message. The else block divides the numerator by the denominator if the if-statement is false. The catch block catches and throws the Arithmetic Exception and displays the message on the console:
try
{
int numerator =10 , denominator =0; //integer variables
if(denominator == 0)
{
throw new ArithmeticException ("An exception occurred"); //throws an exception
}
else
{
System.out.println(numerator/denominator);
}
}
catch(ArithmeticException e)
{
System.out.println(e);
}
Complete Code & Output
Example 3: How to Throw a Java Exception in the Method Header?
The throws keyword can declare multiple exceptions. The throws exception uses multiple catch blocks and displays the exception that matches the relevant try-catch block.
Syntax
The syntax is given as follows:
public static void main(String[] args) throws Excep1, Excep2, ... { //program logic }
Difference Between Throw and Throws
The terms “throw” and “throws” are often perceived to be the same. However, the below table demonstrates the difference between the two:
Throw | Throws |
The throw statement is used within the method body. | The throws keyword is used in the message header. |
The throw statement throws only one exception. | It throws multiple and distinct exceptions. |
In its syntax, the throw statement uses an instance/object for throwing an exception. | The throws keyword uses the Class to throw exceptions in Java. |
In this example, multiple catch blocks are used to throw exceptions. Only those exceptions will be thrown that match the relevant catch blocks. Inside the try block, the for loop traverses the elements of the declared array. In our case, the try block will throw an arithmetic exception because a numeric value cannot be divided by 0. The catch block contains different exceptions such as ArrayIndexOutOfBoundsException and ArithmeticException:
int [ ] numArray= {5,4,5,6,7};
try {
for(int i=0; i<numArray.length;i++)
{
System.out.println(numArray[i]/0);
}
}
catch(ArrayIndexOutOfBoundsException e)
{
throw new ArrayIndexOutOfBoundsException("Index Out of Bound Exception");
}
catch(ArithmeticException e){
throw new ArithmeticException("Arithmetic Exception has occurred");
}
Complete Code & Output
This sums up the implementation of throwing exceptions in Java.
ConclusionTo throw a Java exception, use the “throw” statement to create a new Exception with a custom message. The thrown exception is caught by the relevant catch block. The throw statement is used to declare a single Exception with a human-readable description of the occurred error. On the other hand, the throws keyword declares multiple exceptions. The throw statement optimizes the code performance. However, note that the excessive use of this statement is not encouraged. In this article, there are various exceptions thrown using the throw statement.