Difference between throws and throw in Java

1. Introduction

In Java, exception handling is a powerful mechanism that handles runtime errors to maintain normal application flow. Two keywords used in exception handling are throw and throws. The throw keyword is used to explicitly throw an exception from a method or any block of code. On the other hand, throws is used in a method's signature to declare that the method may throw exceptions that must be caught or declared by the calling method.

2. Key Points

1. throw is used within a method to throw an exception.

2. throws is used in a method declaration to indicate that it can throw specified exceptions.

3. throw initializes a new exception object and then throws it.

4. throws works with multiple exceptions, allowing a method to declare that it may throw more than one type of exception.

3. Differences

throw throws
Used to actually throw an exception. Used to declare that a method might throw an exception.
Throws a single exception. Can declare multiple exceptions.
Followed by an instance of Exception (or subclass). Followed by exception class names (or subclasses).

4. Example


public class ExceptionHandling {

    // Method that uses throw
    public static void simulateError() {
        // Step 1: Use throw to simulate an error by throwing an ArithmeticException
        throw new ArithmeticException("Demo exception - this is thrown using throw");
    }

    // Method that declares exceptions using throws
    public static void riskyMethod() throws ArithmeticException, NullPointerException {
        // Step 2: The method does not throw any exception itself, but it could do, hence the throws declaration
    }

    public static void main(String[] args) {
        try {
            simulateError();
        } catch (ArithmeticException e) {
            System.out.println(e.getMessage());
        }

        try {
            riskyMethod();
        } catch (Exception e) {
            // Step 3: Catch any exceptions that might be thrown by riskyMethod
            System.out.println(e.getMessage());
        }
    }
}

Output:

Demo exception - this is thrown using throw

Explanation:

1. simulateError method uses the throw keyword to explicitly throw an ArithmeticException.

2. riskyMethod method uses the throws keyword to declare that it might throw either an ArithmeticException or a NullPointerException.

3. The main method catches the ArithmeticException thrown by simulateError and would also catch any exceptions thrown by riskyMethod.

5. When to use?

- Use throw when you want to create an exception and hand it off to the runtime to be handled.

- Use throws when you want to declare that your method could throw exceptions, but you do not want to handle them within the same method.

Comments