Skip to content

Throw Statement in Java

The throw statement in Java is used to explicitly throw an exception. It is a way for a programmer to create their own exceptions and throw them manually in a program, signaling that an exceptional condition has occurred.


Syntax of Throw Statement

throw new ExceptionType(“Exception message”);

  • ExceptionType is the type of exception you want to throw (e.g., ArithmeticException, NullPointerException, CustomException).
  • The string message is optional, but it helps to provide more context about the exception.

Key Points About the throw Statement

  1. Manual Exception Throwing:
    1. Unlike throws, which is used to declare exceptions that a method might throw, throw is used within a method to actually throw an exception.
  2. Checked vs. Unchecked Exceptions:
    1. You can throw both checked exceptions (e.g., IOException, SQLException) and unchecked exceptions (e.g., RuntimeException, NullPointerException).
    1. If you throw a checked exception, you must either catch it or declare it with the throws keyword in the method signature.
  3. Execution Flow:
    1. When a throw statement is executed, it immediately stops the current execution and transfers control to the nearest catch block or propagates the exception up the call stack.

Example of Throw Statement

public class ThrowExample {

    public static void main(String[] args) {

        try {

            checkAge(15);

        } catch (Exception e) {

            System.out.println(“Caught an exception: ” + e.getMessage());

        }

    }

    public static void checkAge(int age) throws Exception {

        if (age < 18) {

            throw new Exception(“Age must be 18 or older to access this content.”);

        }

        System.out.println(“Access granted.”);

    }

}

Explanation:

  • The checkAge method throws an exception if the age is less than 18.
  • The throw statement is used to create and throw the Exception with a custom message.
  • The main method catches the thrown exception and prints a message.

Output:

Caught an exception: Age must be 18 or older to access this content.


Throwing Custom Exceptions

You can create your own custom exception classes by extending the Exception class or its subclasses. This allows for more specific and meaningful exception handling.

Example of Custom Exception

class AgeNotEligibleException extends Exception {

    public AgeNotEligibleException(String message) {

        super(message);

    }

}

public class CustomThrowExample {

    public static void main(String[] args) {

        try {

            checkAge(16);

        } catch (AgeNotEligibleException e) {

            System.out.println(“Caught a custom exception: ” + e.getMessage());

        }

    }

    public static void checkAge(int age) throws AgeNotEligibleException {

        if (age < 18) {

            throw new AgeNotEligibleException(“Age must be 18 or older to access this content.”);

        }

        System.out.println(“Access granted.”);

    }

}

Explanation:

  • The AgeNotEligibleException is a custom exception class that extends Exception.
  • The throw statement in checkAge creates an instance of AgeNotEligibleException and throws it.
  • The main method catches and handles the custom exception.

Output:

Caught a custom exception: Age must be 18 or older to access this content.


Difference Between throw and throws

  • throw:
    • Used inside a method to actually throw an exception.
    • throw is followed by an exception object.
  • throws:
    • Used in a method signature to indicate that a method might throw one or more exceptions.
    • It does not throw the exception directly but informs the compiler and developers about the possibility.

Example of throws

public void myMethod() throws IOException {

    // Code that may throw IOException

}


Best Practices for Using throw

  1. Use Descriptive Messages:
    1. Provide clear and informative messages when throwing exceptions to aid in debugging.
  2. Use Custom Exceptions for Specific Cases:
    1. Create custom exception classes for application-specific error handling to improve code readability and maintainability.
  3. Handle Exceptions Gracefully:
    1. Always have appropriate try-catch blocks to handle exceptions thrown using throw.

Conclusion

The throw statement in Java is a powerful tool for manually triggering exceptions to indicate that an exceptional condition has occurred. It enhances the ability to create robust and user-defined error handling by allowing you to throw exceptions explicitly. Whether using built-in exceptions or creating custom exceptions, using throw correctly ensures better control over the flow of your program and effective error handling.