How to Throw an Exception in Java?

How to Throw an Exception in Java?

In this tutorial, we will learn about how to throw an exception in Java. In Java, an Exception is a unique event that disrupts the normal execution flow of a program and signals an error or an exceptional condition. It represents a deviation from the expected behavior and serves as a mechanism for handling and recovering from unexpected situations.

In Java, you can throw an exception using the throw keyword.

Throw Keyword in Java

Throwing an exception in Java involves using the throw keyword to disrupt the normal flow of a program and indicate an error or exceptional condition. Here’s some following steps on how to throw an exception in Java:

  • Select the appropriate exception class: Java provides a variety of exception classes for different types of errors or exceptional situations. You can choose from built-in exceptions like NullPointerException, IllegalArgumentException, ArrayIndexOutOfBoundsException, or create your own custom exception by extending the Exception class.
  • Instantiate the exception: Create an instance of the chosen exception class using the new keyword. You can include a descriptive message to provide details about the exception if necessary.
  • Throw the exception: Use the throw keyword followed by the instance of the exception you created. This action will interrupt the regular program flow and transfer control to an appropriate exception handler.

By utilizing the throw keyword, we gain control over the program’s execution flow and effectively communicate exceptional conditions or errors. This empowers us to handle and recover from unexpected situations by transferring control to an appropriate exception handler.

Syntax:

throw <exception>;

In the syntax, <exception> refers to the instance of an exception that you want to throw. This can be a built-in exception class or a custom exception class that extends the base Exception class.

Different Examples of Throw an Exception in Java

Example 1:

public class Example {
    public static void main(String[] args) {
        try {
            throw new NullPointerException("Custom exception message");
        } catch (NullPointerException e) {
            System.out.println("Exception caught: " + e.getMessage());
        }
    }
}


Output:

Exception caught: Custom exception message

In this example, we actively employ the throw keyword to throw a NullPointerException by creating an instance of the exception class with a customized message. Subsequently, the catch block is utilized to catch and handle the thrown exception.

Example 2:

public class Example {
    public static void main(String[] args) {
        try {
            int age = -18;
            if (age < 0) {
                throw new IllegalArgumentException("Age cannot be negative.");
            }
            System.out.println("Age: " + age);
        } catch (IllegalArgumentException e) {
            System.out.println("Error: " + e.getMessage());
        }
    }
}


Output:

Error: Age cannot be negative.

In this example, we are checking the value of the age variable. If the age is less than 0 (negative), we actively throw a IllegalArgumentException by creating an instance of the exception class with a custom message stating that “Age cannot be negative.”

Difference between throw and throws keywords in Java

throwthrows
FunctionalityThe throw keyword is used to explicitly raise or throw an exception within a method. The throws keyword is used in method declarations to specify the exceptions that a method might throw.
InvocationThe throw keyword is used within the body of a method to throw an exception at a specific point.The throws keyword appears in the method signature, indicating that the method might throw one or more exceptions.
HandlingWhen an exception is thrown using the throw keyword, it must be caught and handled using try-catch blocks within the same method or in any higher-level method in the call stackthrows keyword indicates that the method does not handle those exceptions itself but instead passes the responsibility to the calling code to handle or propagate them further.
UsageIt allows you to actively indicate exceptional conditions or errors and transfer control to an appropriate exception handler.It is used to declare the types of exceptions that can be propagated to the calling code.
Syntaxthrow <exception>;() throws {
// Method body
}

Discover Our Exciting Courses and Quiz

Enroll now to enhance your skills and knowledge!

Java Online Quiz

Level up your coding skills with our interactive programming quiz!