Uncategorized

Difference Between throw and throws in Java (with Examples)

TGTeam GyaniPanditNovember 21, 20265 min read

throw and throws look almost the same, and both belong to exception handling in Java, but they do different jobs. throw actually raises an exception at a point inside your code. throws only declares, in a method’s signature, that the method might pass certain exceptions to whoever calls it.

throw vs throws at a Glance

throw throws
What it does Raises an exception right now Warns callers that the method may pass on an exception
Where it is written Inside a method or block In the method declaration, after the parameter list
Followed by An exception object: throw new IllegalArgumentException("...") Exception class names: throws IOException
How many One exception object at a time Several, separated by commas
Effect on the program Normal flow stops immediately None by itself; it is information for the compiler and the caller
Typical use Rejecting invalid input, signalling a business rule failure, re-throwing Declaring checked exceptions you do not want to handle inside the method

The throw Keyword

Use throw when your code detects a problem and wants to stop and report it. The syntax is:

throw new ExceptionType("message");
public class ThrowDemo {
    static void setAge(int age) {
        if (age < 0) {
            throw new IllegalArgumentException("Age cannot be negative: " + age);
        }
        System.out.println("Age set to " + age);
    }

    public static void main(String[] args) {
        setAge(21);
        try {
            setAge(-5);
        } catch (IllegalArgumentException e) {
            System.out.println("Caught: " + e.getMessage());
        }
    }
}

Output:

Age set to 21
Caught: Age cannot be negative: -5

If you remove the try-catch, nothing catches the exception and the program ends with an error that begins like this, followed by the stack trace:

Exception in thread "main" java.lang.IllegalArgumentException: Age cannot be negative: -5

IllegalArgumentException is an unchecked exception, so setAge() did not need a throws clause.

The throws Keyword

Java forces you to deal with checked exceptions, such as IOException. You have two choices: catch the exception inside the method, or declare it with throws and let the caller handle it.

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

public class ThrowsDemo {
    static void openFile(String name) throws IOException {
        try (FileReader reader = new FileReader(name)) {
            System.out.println("File opened: " + name);
        }
    }

    public static void main(String[] args) {
        try {
            openFile("notes.txt");
        } catch (IOException e) {
            System.out.println("Could not open file: " + e.getMessage());
        }
    }
}

Output (when notes.txt does not exist, on Linux or macOS):

Could not open file: notes.txt (No such file or directory)

On Windows the message ends with “(The system cannot find the file specified)” instead.

If you delete throws IOException from openFile() and do not catch the exception there either, the code will not compile. The compiler reports an error like:

error: unreported exception FileNotFoundException; must be caught or declared to be thrown

Using throw and throws Together: A Custom Exception

The two keywords often appear together. Here a bank-style method throws a custom checked exception and declares it with throws:

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

public class BankDemo {
    static int balance = 500;

    static void withdraw(int amount) throws InsufficientBalanceException {
        if (amount > balance) {
            throw new InsufficientBalanceException(
                "Insufficient balance. Available: " + balance + ", requested: " + amount);
        }
        balance -= amount;
        System.out.println("Withdrawn: " + amount + ", balance left: " + balance);
    }

    public static void main(String[] args) {
        try {
            withdraw(200);
            withdraw(800);
        } catch (InsufficientBalanceException e) {
            System.out.println("Error: " + e.getMessage());
        }
    }
}

Output:

Withdrawn: 200, balance left: 300
Error: Insufficient balance. Available: 300, requested: 800

Because InsufficientBalanceException extends Exception (not RuntimeException), it is checked, so withdraw() must declare it with throws.

Declaring More Than One Exception

void loadData(String path) throws IOException, InterruptedException {
    // reading a file and waiting for another thread
}

Re-throwing an Exception

throw can also be used inside a catch block, for example to wrap a low-level exception in a clearer one while keeping the original as the cause:

try {
    openFile("settings.txt");
} catch (IOException e) {
    throw new RuntimeException("Could not load settings", e);
}

Rules to Remember

  • You can only throw objects of Throwable or its subclasses.
  • Any statement written directly after throw in the same block is unreachable, and the compiler rejects it.
  • Checked exceptions must be either caught or declared with throws. Unchecked exceptions (subclasses of RuntimeException and Error) do not need to be declared.
  • An overriding method cannot declare new or broader checked exceptions than the method it overrides.
  • throws does not handle anything. Somewhere up the call chain, the exception still has to be caught, or the program stops.

Frequently Asked Questions

What is the main difference between throw and throws in Java?

throw creates and raises an exception inside a method. throws appears in the method signature and declares which exceptions the method may pass to its caller.

Can we throw multiple exceptions with throw?

No, one throw statement throws one exception object. You can, however, list several exception classes after throws.

Is throws necessary for unchecked exceptions?

No. You may write it for documentation, but the compiler only requires it for checked exceptions.

Can main() use throws?

Yes, for example public static void main(String[] args) throws IOException. If the exception reaches main and is not caught, the program ends and prints the stack trace.

Related: Java methods

Turn reading into skillsCertificate courses in AI, Data Science and programming.
Explore Courses