When working with Java, the throw keyword is utilized to deliberately raise an exception within a method or a code block. This functionality enables programmers to indicate the presence of an error that requires proper handling. It is essential that the exception being thrown is an object of Throwable or any of its derived classes like Exception or RuntimeException.
Java throw Keyword
The throw keyword in Java is employed to explicitly raise an exception from a method or code block. It enables the throwing of both checked and unchecked exceptions, particularly custom exceptions. This functionality allows developers to intentionally trigger an exception when a specific undesired scenario arises.
We define the specific exception object to be raised, containing a message that describes the error. These exceptions can pertain to various scenarios such as user inputs, server issues, hardware failures, incorrect calculations, or any other conditions based on the program's needs.
It is also possible to establish custom conditions and trigger an exception explicitly by employing the throw keyword. For instance, if we perform a division operation with one number divided by another number, we can trigger an ArithmeticException. In this scenario, we simply need to define the condition and initiate the exception using the throw keyword.
Syntax:
throw new exception_class("error message");
An Instance denotes an object belonging to a class that is required to be a subclass of Throwable, encompassing classes like Exception and its derived classes.
Let's see an example of throw IOException.
throw new IOException("sorry device error");
Below:
- The keyword
- is employed for generating a new instance (object) of the exception class.
- The error message offers information regarding the cause of the exception.
The instance should be of the type Throwable or a subclass of Throwable. For instance, Exception is a subclass of Throwable, and custom exceptions created by users typically extend the Exception class.
Key Requirements
- The object we throw must be of type Throwable or one of its subclasses.
- For example, Exception is a subclass of Throwable.
- User-defined exceptions (also known as custom exceptions) usually extend the Exception class.
- If you throw a checked exception and do not handle it inside the method, you must declare it using the throws keyword in the method signature.
Why Use throw in Java?
Manually throwing exceptions allows programmers to:
- Validate inputs (for example, throwing an exception if user input is invalid).
- Handle specific conditions (for example, throwing exceptions if a requested resource is not found).
- Create more meaningful error messages that are specific to the application's context.
- Improve debugging by providing custom error information.
Java throw Keyword Example
Example 1: Throwing an Unchecked Exception
In this instance, a function called validate has been established to take an integer as an argument. When the age is under 18, an ArithmeticException is thrown; alternatively, a greeting message for voting eligibility is displayed.
Implementation
Example
import java.lang.ArithmeticException;
public class Main {
// Function to check if a person is eligible to vote or not
public static void validate(int age) {
if(age < 18) {
// Throw ArithmeticException if not eligible to vote
throw new ArithmeticException("Person is not eligible to vote");
} else {
System.out.println("Person is eligible to vote!!");
}
}
// Main method
public static void main(String args[]) {
// Calling the function
validate(13);
System.out.println("rest of the code...");
}
}
Output:
Exception in thread "main" java.lang.ArithmeticException: Person is not eligible to vote
at Main.validate(Main.java:8)
at Main.main(Main.java:17)
The code mentioned above generates an unchecked exception. Likewise, we have the ability to throw unchecked exceptions as well as exceptions defined by the user.
Note: If we throw an unchecked exception from a method, it is not required to handle the exception or declare it in a throws clause. However, for checked exceptions, handling or declaration in the throws clause is mandatory."
When a checked exception is thrown using the throw keyword, it is necessary to either handle the exception using the catch block or declare it in the method signature using the throws declaration.
Example 2: Throwing a Checked Exception
In Java, checked exceptions are exceptions that must be dealt with either by using a try-catch block or by specifying them in the method signature with the throws keyword as mandated by the compiler. These exceptions commonly originate from external activities like file handling, network communications, or database interactions that are susceptible to errors.
Checked exceptions, unlike unchecked exceptions that extend the RuntimeException class, are subclasses of Exception but do not extend the RuntimeException class.
In this instance, we showcase the process of raising a checked exception (specifically FileNotFoundException) by utilizing the throw keyword and effectively managing it through a try-catch block.
Note: Every subclass of Error and RuntimeException is an unchecked exception in Java. A checked exception is everything else under the Throwable class.
Example
import java.io.*;
public class Main {
//function to check if a person is eligible to vote or not
public static void method() throws FileNotFoundException {
FileReader file = new FileReader("C:\\Users\\Desktop\\abc.txt");
BufferedReader fileInput = new BufferedReader(file);
// Explicitly throwing a checked exception
throw new FileNotFoundException();
}
//main method
public static void main(String args[]){
try {
method();
}
catch (FileNotFoundException e) {
e.printStackTrace();
}
System.out.println("rest of the code...");
}
}
Output:
java.io.FileNotFoundException: C:\Users\Desktop\abc.txt (No such file or directory)
at java.base/java.io.FileInputStream.open0(Native Method)
at java.base/java.io.FileInputStream.open(FileInputStream.java:213)
at java.base/java.io.FileInputStream.<init>(FileInputStream.java:152)
at java.base/java.io.FileInputStream.<init>(FileInputStream.java:106)
at java.base/java.io.FileReader.<init>(FileReader.java:60)
at Main.method(Main.java:9)
at Main.main(Main.java:20)
Example 3: Throwing User-Defined Exception
Exceptions other than those specified under the Throwable class encompass a wide range of scenarios. In Java, developers have the capability to generate personalized exceptions by extending either the Exception class or its derived classes. Such exceptions are referred to as user-defined exceptions. They prove to be valuable when there is a necessity to uphold rules and restrictions specific to an application that are not addressed by Java's standard exceptions.
In this instance, we are going to create a personalized exception named UserDefinedException and trigger it manually by utilizing the throw keyword. Subsequently, we will capture and manage it by employing a try-catch block, similar to how we handle any other verified exception.
Example
import java.io.*;
// class represents a user-defined exception
class UserDefinedException extends Exception {
public UserDefinedException(String str) {
// Calling the constructor of the parent Exception
super(str);
}
}
// Class that uses the above MyException
public class Main {
public static void main(String args[]) {
try {
// throw an object of user user-defined exception
throw new UserDefinedException("This is user-defined exception");
}
catch (UserDefinedException ude) {
System.out.println("Caught the exception");
// Print the message from the MyException object
System.out.println(ude.getMessage());
}
}
}
Output:
Caught the exception
This is a user-defined exception
Java throw keyword MCQ
- Which of the following is true about the throw keyword in Java?
- It is used to declare an exception.
- It is used to handle an exception.
- It is used to explicitly throw an exception.
- It is used to define a custom exception.
Explanation: The throw keyword in Java is used to explicitly throw an exception, either a checked or unchecked exception, from any part of the code. It is different from exception handling, which is done using try, catch, and finally.
- When a method throws a checked exception, what must the method declare?
- It must declare the exception using the throws keyword.
- It must catch the exception within the method.
- It must use a try block within the method.
- It must ignore the exception.
Explanation: When a method throws a checked exception, it must declare that it throws the exception using the throws keyword in its method signature. It informs callers of the method that they must handle or further declare the exception.
- Which of the following statements is false regarding custom exceptions in Java?
- Custom exceptions must extend the Exception class.
- Custom exceptions can extend the RuntimeException class.
- Custom exceptions cannot have constructors.
- Custom exceptions can include additional methods and fields.
The assertion is inaccurate as custom exceptions frequently include constructors. These constructors enable the customization of error messages or additional information during the exception throwing process.
- Take into account the subsequent method declaration:
public void myMethod() throws IOException, SQLException { ... }
Which of the following is true about the myMethod declaration?
- myMethod must handle both IOException and SQLException within the method.
- myMethod must not throw any exceptions.
- myMethod declares that it may throw IOException and SQLException, and these must be handled by its caller.
- myMethod can only throw IOException and not SQLException.
Explanation: The method myMethod declares that it may throw IOException and SQLException. Any caller of myMethod must handle these exceptions using a try-catch block or declare them in its own throws clause.
- Which of the following correctly describes the behavior of the finally block when an exception is thrown?
- The finally block is executed only if no exception is thrown.
- The finally block is executed only if an exception is thrown.
- The finally block is executed regardless of whether an exception is thrown.
- The finally block is executed only for unchecked exceptions.
The finally block is a crucial part of exception handling in programming. It is guaranteed to execute, irrespective of whether an exception is raised or not. This block is commonly employed for tasks like releasing resources, closing files, or freeing up network resources to ensure these operations are carried out regardless of any exceptions that may occur.