Course contentsShow
← Java
Lesson 739 of 2,87018. Exception Handling FundamentalsFree lesson

The throw Keyword: Throwing Exceptions Manually

Learn how to use the throw keyword to explicitly raise exceptions in your code when error conditions occur.

The throw Keyword: Throwing Exceptions Manually

What you'll learn: How to use the throw keyword to explicitly raise exceptions when your code detects an error condition.

What Is Throwing an Exception?

So far, you've seen how to catch exceptions that Java throws automatically (like NullPointerException or ArrayIndexOutOfBoundsException). But what if you need to signal that something has gone wrong in your own code? That's where the throw keyword comes in.

The throw keyword lets you manually create and raise an exception, transferring control to the nearest appropriate catch block (or terminating the program if no handler exists).

Basic Syntax

throw new ExceptionType("Error message");

You create an exception object using new, then use throw to raise it. The exception message helps whoever catches it understand what went wrong.

A Simple Example

public class AgeValidator {
    public static void checkAge(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) {
        try {
            checkAge(25);  // Valid
            checkAge(-5);  // Triggers exception
        } catch (IllegalArgumentException e) {
            System.out.println("Caught: " + e.getMessage());
        }
    }
}

Here, when we detect invalid data (negative age), we throw an exception rather than letting the method continue with bad input.

Why Throw Exceptions Manually?

Think of throw as pulling the emergency brake. When your code detects a condition it can't handle safely—invalid input, broken assumptions, unrecoverable errors—you use throw to stop normal execution and signal "something is wrong."

Key Takeaway: The throw keyword lets you manually raise exceptions when your code detects error conditions, giving you control over when and how errors are signaled to calling code.