Course topics

By WebNest Studio Engineering Team

Java - Core Tutorial

throw and throws

throw and throws look similar but do entirely different jobs. throw is a statement used inside a method body to actually raise an exception at a specific point in the code. throws is a declaration used in a method's signature to announce that the method might propagate a particular checked exception to its caller, without handling it itself.

Why it matters

throw and throws are one letter apart and do different jobs: one raises an exception, the other warns callers that a method may raise one. You use throw to reject invalid input at the edge of a method, and throws to pass a problem to code that is better placed to deal with it.

The throw Statement

throw is followed by a single exception object, and it immediately transfers control out of the current method, just like a return statement, except it hands control to the nearest matching catch block instead of the caller's next line. You can throw a newly created exception (throw new IllegalArgumentException("invalid input")) or re-throw one you already caught. Execution after a throw statement in the same block is unreachable and will not compile if it consists of ordinary statements.

The throws Declaration

throws appears after a method's parameter list and lists one or more checked exception types the method does not handle internally, forcing any caller to either catch them or declare them further up the call chain. This is how the compiler enforces that checked exceptions are never silently dropped anywhere in a call chain. Unchecked exceptions (RuntimeException and its subclasses) never need to be declared with throws, although you are allowed to document them that way for clarity.

  • throw: a statement, appears in a method body, throws exactly one exception instance.
  • throws: a declaration, appears in a method signature, lists one or more exception types.
  • A method that calls another method declaring throws must catch that exception or declare it too.

Example

throw inside a method, and throws propagating a checked exception to the caller

Java
import java.io.IOException;

public class ThrowThrowsDemo {

    static void readConfig(boolean fileMissing) throws IOException {
        if (fileMissing) {
            throw new IOException("config.txt not found");
        }
        System.out.println("Config loaded successfully.");
    }

    public static void main(String[] args) {
        try {
            readConfig(true);
        } catch (IOException e) {
            System.out.println("Handled: " + e.getMessage());
        }
    }
}
Output
Handled: config.txt not found

Common Mistakes

  • Confusing throw (a statement that raises one exception) with throws (a declaration that lists possible exception types).
  • Forgetting to add throws to a method signature after it calls another method that declares a checked exception, causing a compile error.
  • Writing "throw new Exception();" without a message, leaving no useful information for whoever eventually catches it.
  • Declaring throws Exception broadly instead of the specific checked exception type, hiding what can actually go wrong from callers.

Exercise

Make setAge reject negative values by throwing an IllegalArgumentException with the message Age cannot be negative. In main, catch the exception and print its message.

Expected output: Age set to 25 then Age cannot be negative

Java · starter code
public class AgeCheck {

    static void setAge(int age) {
        // TODO: throw IllegalArgumentException for a negative age
        System.out.println("Age set to " + age);
    }

    public static void main(String[] args) {
        setAge(25);
        // TODO: call setAge(-3) and print the message of the exception it throws
    }
}
Show hints
  • Create and raise the exception in one statement: throw new IllegalArgumentException("...");
  • e.getMessage() returns the text passed to the constructor.
Show solution
Java · solution
public class AgeCheck {

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

    public static void main(String[] args) {
        setAge(25);
        try {
            setAge(-3);
        } catch (IllegalArgumentException e) {
            System.out.println(e.getMessage());
        }
    }
}

Quick quiz

1. What does the throw keyword do?

  • A. Declares that a method may fail
  • B. Ignores an exception
  • C. Catches an exception
  • D. Raises an exception object at that point in the code
Show answer

D. throw is a statement that raises an exception immediately. Declaring possible exceptions is the job of throws.

2. Where does throws appear?

  • A. In the method signature, after the parameter list
  • B. Inside a method body
  • C. In a catch block
  • D. Before the class name
Show answer

A. throws is part of the method declaration and lists the exception types the method may pass to its caller.

3. Method load() is declared with throws IOException. A caller invokes it without a try-catch and without declaring throws. What happens?

  • A. It compiles and may fail at runtime
  • B. It does not compile
  • C. The exception is ignored
  • D. A warning is shown but it compiles
Show answer

B. IOException is a checked exception. The caller must either catch it or declare it, and the compiler enforces this.

Interview questions

What is the difference between throw and throws?

Show answer

throw is a statement inside a method body that raises one exception object. throws is part of a method's declaration and lists the exception types the method may let escape to its caller. throw is followed by an instance; throws is followed by one or more class names.

Should every method that can fail declare throws?

Show answer

Only for checked exceptions the method does not handle itself; the compiler requires those. Unchecked exceptions such as IllegalArgumentException do not need to be declared, though documenting them is helpful. Declaring a broad throws Exception everywhere defeats the purpose, because it tells the caller nothing about what can actually go wrong.

Key Points to Remember

  • throw is a statement that raises exactly one exception object at runtime.
  • throws is part of a method signature, declaring checked exceptions the method does not handle itself.
  • Only checked exceptions must be declared with throws; unchecked exceptions are optional to declare.
  • A checked exception must be caught or re-declared at every level of the call chain until something handles it.

Practice in the playground

Write and run your own code for this topic, or start from the exercise or an example. Runs plain Java 17. Frameworks such as Spring, and databases, are not available here. Your code for each topic is kept in this browser.

Run the examples

Change an input, predict the result, then compare it with the output. Explain why the result changes.

WebNest Studio

Written by

WebNest Studio Engineering Team

Practical lessons from developers working with Java, Python, React, databases and production systems.

Led by Vansh Duggal, Founder, WebNest Studio · Full-stack & software engineering