Throw Keyword

Throw Keyword

A school program needs reliable data and clear rules. Throw explicitly raises an exception object. A mark validator can reject a value outside the agreed range instead of continuing with invalid state.

  1. Understand

    Throw explicitly raises an exception object.

  2. Apply

    Trace the Java example, predict its output and explain the result before running it.

  3. Avoid mistakes

    Throw raises one exception; throws declares possible checked exceptions on a method. These keywords have different jobs.

throw Keyword in Java

In Java, exceptions can be thrown automatically by the JVM or manually by the programmer. The throw keyword allows developers to deliberately trigger an exception. Why? Sometimes, you want to fail fast or validate input before continuing further. That's where throw shines.

Syntax of throw in Java

The throw statement is used followed by an instance of an exception class:

throw new ExceptionType("Error message");

Example 1: Throwing a Built-in Exception

Let’s say you're writing a function that shouldn’t accept a negative age. Instead of letting the program crash somewhere down the line, you raise a red flag immediately.

public class Main {
    static void validateAge(int age) {
        if (age < 0) {
            throw new IllegalArgumentException("Age cannot be negative");
        }
        System.out.println("Age is valid: " + age);
    }

    public static void main(String[] args) {
        validateAge(-5);
        System.out.println("End of program");
    }
}
Exception in thread "main" java.lang.IllegalArgumentException: Age cannot be negative
    at Main.validateAge(Main.java:4)
    at Main.main(Main.java:9)

What Happened?

We manually threw an IllegalArgumentException when the age was invalid. As soon as it was thrown, the normal flow stopped, and the program exited before reaching the final print statement.

Example 2: Using throw with Custom Exceptions

Sometimes, built-in exceptions aren't descriptive enough. You can create your own custom exceptions and throw them using the same throw keyword.

// Define a custom exception
class LowBalanceException extends Exception {
    public LowBalanceException(String message) {
        super(message);
    }
}

public class Bank {
    static void withdraw(int amount) throws LowBalanceException {
        if (amount > 1000) {
            throw new LowBalanceException("Withdrawal amount exceeds limit");
        }
        System.out.println("Withdrawn: " + amount);
    }

    public static void main(String[] args) throws LowBalanceException {
        withdraw(1500);
    }
}
Exception in thread "main" LowBalanceException: Withdrawal amount exceeds limit
    at Bank.withdraw(Bank.java:9)
    at Bank.main(Bank.java:14)

Deep Dive: How throw Works

  • It throws an object — not a class name. That’s why you must use new.
  • It halts execution — control transfers to the nearest matching catch block or crashes the program if uncaught.
  • It can throw only objects of type Throwable — which includes Exception and Error.

When to Use throw

Use it to:

  • Enforce business rules (e.g., age must be > 18)
  • Validate inputs
  • Handle invalid states
  • Fail fast and exit on unexpected conditions

Common Mistakes to Avoid

  • Trying to throw a class instead of an object (e.g., throw IOException; instead of throw new IOException();)
  • Forgetting to declare throws in the method signature if the exception is checked
  • Throwing non-Throwable objects (like String or int)

Real-Life Analogy

Think of throw as pulling the fire alarm in a building. You're not solving the problem (that’s for try-catch to handle), but you're raising the alert that something went wrong and needs attention. Immediate action is taken — either someone catches it or the whole system shuts down.

Important boundaries and mistakes

Throw raises one exception; throws declares possible checked exceptions on a method. These keywords have different jobs.

Try the school example

Before running this Java program, write down each line you expect to see. Identify the value, branch, object or exception responsible for each line. Then explain whether the following assumption is valid: Throw raises one exception; throws declares possible checked exceptions on a method.

Java 17 · Main.java · complete practice program

public class Main  {
  static void checkMark(int mark)  {
    if (mark < 0 || mark > 100) throw new IllegalArgumentException("mark");
  }
  public static void main(String[] args)  {
    try  {
      checkMark(-1);
    }
    catch (IllegalArgumentException e)  {
      System.out.println("Invalid mark");
    }
  }
}

Now change one thing: Call checkMark(72). Predict the new behavior before checking the worked variation.

Worked answer and reasoning

Java 17 · Main.java · source repeated for this answer

public class Main  {
  static void checkMark(int mark)  {
    if (mark < 0 || mark > 100) throw new IllegalArgumentException("mark");
  }
  public static void main(String[] args)  {
    try  {
      checkMark(-1);
    }
    catch (IllegalArgumentException e)  {
      System.out.println("Invalid mark");
    }
  }
}

Expected output

Invalid mark

Throw explicitly raises an exception object. A mark validator can reject a value outside the agreed range instead of continuing with invalid state.

Throw raises one exception; throws declares possible checked exceptions on a method. These keywords have different jobs.

Run with javac Main.java, then java Main. The declaration of Main names the class; main starts the example, and println writes a complete output line.

Worked variation: Call checkMark(72). No exception is raised, so the catch message is skipped.

Check your understanding

For the complete practice program in this lesson, which output is expected on Java 17?
Choose one answer. You can try again.

Answer and explanation

Invalid mark

Throw explicitly raises an exception object. A mark validator can reject a value outside the agreed range instead of continuing with invalid state. Throw raises one exception; throws declares possible checked exceptions on a method. These keywords have different jobs.

Check a common mistake

How does throw differ from throws?
Choose one answer. You can try again.

Answer and explanation

Throw raises an exception object; throws declares exceptions a method may propagate.

Raising, declaring and recovering are separate actions. A catch handler or caller must implement the recovery behavior.

What to remember

Throw explicitly raises an exception object. A mark validator can reject a value outside the agreed range instead of continuing with invalid state. Throw raises one exception; throws declares possible checked exceptions on a method. These keywords have different jobs.

Related explanations: Java Variables, Java If Statement - Syntax and Examples, Java Class - Blueprint of Objects, Exceptions in Java Introduction.

Supporting documentation: Official Java learning guide and Java 17 language specification.

Reaching the recap and completing the quizzes are separate milestones.

    Next lesson: Throws Keyword →