throw statement

The throw statement in Java is used to explicitly throw an exception in your code. When you throw an exception, the normal flow of the program is interrupted, and control is transferred to the nearest catch block that can handle the type of exception thrown. If no suitable catch block is found, the program terminates.

Key Points:

  1. Purpose of throw: It is used to explicitly throw an exception, either pre-defined (like NullPointerException, IOException) or custom exceptions (user-defined classes extending Exception).

  2. Exception Type: When throwing an exception, you must throw an instance of a subclass of Throwable, typically Exception or Error. It can be a checked exception or an unchecked exception.

  3. Program Control: Once the exception is thrown, the normal flow of the program stops, and control moves to the nearest catch block or to the default exception handler if no handler is found.

Syntax:

throw new ExceptionType("Error message");Code language: JavaScript (javascript)

How throw Works:

  • The throw statement is followed by an instance of an exception class (either built-in or custom).

  • The exception can then be caught and handled by a catch block, or the method signature must declare it with throws if the exception is checked.

Example 1: Throwing a Checked Exception

In this example, a throw statement is used to throw a checked exception IOException.

import java.io.IOException;

public class ThrowCheckedException {
    public static void main(String[] args) {
        try {
            checkFile("invalid.txt");
        } catch (IOException e) {
            System.out.println("Caught exception: " + e.getMessage());
        }
    }

    public static void checkFile(String fileName) throws IOException {
        if (fileName.equals("invalid.txt")) {
            throw new IOException("File not found: " + fileName);  // Throwing checked exception
        }
    }
}

Example 2: Throwing an Unchecked Exception

In this example, a throw statement is used to throw an unchecked exception NullPointerException.

public class ThrowUncheckedException {
    public static void main(String[] args) {
        try {
            processObject(null);  // This will cause an exception to be thrown
        } catch (NullPointerException e) {
            System.out.println("Caught exception: " + e.getMessage());
        }
    }

    public static void processObject(Object obj) {
        if (obj == null) {
            throw new NullPointerException("Object cannot be null");  // Throwing unchecked exception
        }
    }
}

Example 3: Throwing a Custom Exception

Here’s how you can create and throw your own custom exceptions in Java.

class InvalidAgeException extends Exception {
    public InvalidAgeException(String message) {
        super(message);  // Call parent constructor to set the error message
    }
}

public class ThrowCustomException {
    public static void main(String[] args) {
        try {
            validateAge(15);  // This will throw a custom exception
        } catch (InvalidAgeException e) {
            System.out.println("Caught exception: " + e.getMessage());
        }
    }

    public static void validateAge(int age) throws InvalidAgeException {
        if (age < 18) {
            throw new InvalidAgeException("Age must be 18 or older");
        }
    }
}

When to Use the throw Statement:

  1. Indicating an Error Condition: When an unexpected or illegal situation arises, such as an invalid argument or missing resource, you can use throw to signal the problem.

  2. Custom Error Handling: When predefined exceptions do not fit the context of your program, you can define your own exception class and throw it.

  3. Preventing Further Execution: Throwing an exception can help stop the normal flow of the program when continuing would lead to inconsistent states or further errors.

Considerations:

  • Checked vs Unchecked: When throwing checked exceptions, you must either handle them in a try-catch block or declare them in the method signature using throws. Unchecked exceptions, however, are not mandatory to catch or declare.

  • Program Control: Once an exception is thrown, the method stops execution, and the control flow moves to the nearest matching catch block, or if no such block is found, it may terminate the program.

The throw statement in Java is an essential mechanism for error handling. It allows you to explicitly signal that something has gone wrong and transfer control to an appropriate error handler. By throwing either predefined or custom exceptions, you can make your application more robust and easier to debug. However, exceptions should not be overused or used for normal control flow, as they can add overhead to the program.

Scroll to Top