JavaError HandlingIntermediate

throw / throws

The `throw` keyword is used to explicitly raise an exception, while the `throws` keyword is used in a method signature to declare that the method might throw one or more checked exceptions.

Review the syntaxStudy the examplesOpen the coding app
throw new ExceptionType("message");
ReturnType methodName(Params) throws ExceptionType1, ExceptionType2 { ... }

This static page keeps the syntax and examples indexed for search, while the coding app handles interactive exploration and saved references.

What it does

Overview

The `throw` keyword is used to explicitly raise an exception, while the `throws` keyword is used in a method signature to declare that the method might throw one or more checked exceptions.

The `throw` and `throws` keywords are integral to Java's exception handling mechanism. `throw` is used within a method body to create and immediately raise an exception object. Once `throw` is executed, the normal flow of the program is interrupted, and the Java runtime searches for an appropriate `catch` block. If no `catch` block is found in the current method, the exception propagates up the call stack. `throws`, on the other hand, is used in a method's signature to indicate that the method might throw certain checked exceptions. This declaration forces callers of the method to either handle these exceptions (using `try-catch`) or re-declare them (`throws`) themselves. This compile-time check ensures that potential error conditions are explicitly acknowledged and handled, leading to more robust code. `throws` is not required for unchecked exceptions (`RuntimeException` and its subclasses) as they are not checked at compile time. Best practices include throwing specific exceptions that accurately describe the error, and using `throws` to document the potential checked exceptions a method can propagate, guiding callers on how to handle them.

Quick reference

Syntax

throw new ExceptionType("message");
ReturnType methodName(Params) throws ExceptionType1, ExceptionType2 { ... }

Inputs

Parameters

ExceptionTypeClass · The type of exception to be thrown or declared (e.g., `IllegalArgumentException`, `IOException`).
message (optional)String · A descriptive message explaining the cause of the exception.

See it in practice

Examples

1

Using throw to raise an exception

public class ThrowExample {
    public static void validateAge(int age) {
        if (age < 0 || age > 120) {
            throw new IllegalArgumentException("Age must be between 0 and 120.");
        }
        System.out.println("Age is valid: " + age);
    }

    public static void main(String[] args) {
        try {
            validateAge(25);
            validateAge(-5);
        } catch (IllegalArgumentException e) {
            System.err.println("Validation error: " + e.getMessage());
        }
    }
}
Output:
Age is valid: 25 Validation error: Age must be between 0 and 120.

The `validateAge` method uses `throw` to explicitly raise an `IllegalArgumentException` if the age is outside the valid range. The `main` method catches this exception.

2

Using throws to declare a checked exception

import java.io.FileReader;
import java.io.IOException;

public class ThrowsExample {
    public static void readFile(String filePath) throws IOException {
        FileReader reader = new FileReader(filePath);
        try {
            int charCode = reader.read();
            System.out.println("First char: " + (char) charCode);
        } finally {
            reader.close();
        }
    }

    public static void main(String[] args) {
        try {
            readFile("nonexistent.txt");
        } catch (IOException e) {
            System.err.println("Caught an I/O exception: " + e.getMessage());
        }
    }
}
Output:
Caught an I/O exception: nonexistent.txt (No such file or directory)

The `readFile` method declares `throws IOException` because `FileReader` and `reader.read()` can throw it. The `main` method is then forced to handle this checked exception.

3

Throwing a custom exception

class InsufficientFundsException extends Exception {
    public InsufficientFundsException(String message) {
        super(message);
    }
}

public class CustomThrowExample {
    private double balance = 1000;

    public void withdraw(double amount) throws InsufficientFundsException {
        if (amount > balance) {
            throw new InsufficientFundsException("Attempted to withdraw " + amount + ", but only " + balance + " available.");
        }
        balance -= amount;
        System.out.println("Withdrawal successful. New balance: " + balance);
    }

    public static void main(String[] args) {
        CustomThrowExample account = new CustomThrowExample();
        try {
            account.withdraw(500);
            account.withdraw(700); // This will throw the custom exception
        } catch (InsufficientFundsException e) {
            System.err.println("Transaction failed: " + e.getMessage());
        }
    }
}
Output:
Withdrawal successful. New balance: 500.0 Transaction failed: Attempted to withdraw 700.0, but only 500.0 available.

A custom checked exception `InsufficientFundsException` is defined and thrown using `throw`. The `withdraw` method declares it with `throws`, and the `main` method handles it.

Debug faster

Common Errors

1

Compile-time Error

Cause: A method throws a checked exception but does not declare it using `throws`.

Fix: Either add the `throws ExceptionType` clause to the method signature or wrap the problematic code in a `try-catch` block within the method.

import java.io.FileReader;
import java.io.IOException;

public class ErrorExample {
    public void readFile() { // Compile-time error: unreported exception IOException
        // FileReader reader = new FileReader("file.txt");
    }
}
2

Runtime Error (Unhandled Exception)

Cause: A method declares an exception with `throws`, but the calling method does not handle or re-declare it.

Fix: The calling method must either enclose the call in a `try-catch` block or declare the exception itself using `throws`.

import java.io.IOException;

class Caller {
    void callMethod() throws IOException { /* ... */ }
}

class Main {
    public static void main(String[] args) { // Compile-time error: unreported exception IOException
        // new Caller().callMethod();
    }
}

Runtime support

Compatibility

JVMN/AJava 1.0+

Source: Oracle Java Documentation

Common questions

Frequently Asked Questions

The `throw` keyword is used to explicitly raise an exception, while the `throws` keyword is used in a method signature to declare that the method might throw one or more checked exceptions.

ExceptionType: The type of exception to be thrown or declared (e.g., `IllegalArgumentException`, `IOException`). message: A descriptive message explaining the cause of the exception.

Compile-time Error: Either add the `throws ExceptionType` clause to the method signature or wrap the problematic code in a `try-catch` block within the method. Runtime Error (Unhandled Exception): The calling method must either enclose the call in a `try-catch` block or declare the exception itself using `throws`.