0
0
JavaHow-ToBeginner · 3 min read

How to Use Throw Keyword in Java: Syntax and Examples

In Java, the throw keyword is used to manually throw an exception object. You write throw followed by an instance of Throwable (usually an Exception) to signal an error condition in your code.
📐

Syntax

The throw statement requires an exception object to be thrown. This object must be an instance of Throwable or its subclasses like Exception or Error.

  • throw: keyword to throw an exception
  • new ExceptionType(): creates the exception object
java
throw new ExceptionType("Error message");
💻

Example

This example shows how to use throw to manually throw an IllegalArgumentException when a method receives a negative number.

java
public class ThrowExample {
    public static void checkNumber(int number) {
        if (number < 0) {
            throw new IllegalArgumentException("Number must be non-negative");
        }
        System.out.println("Number is " + number);
    }

    public static void main(String[] args) {
        checkNumber(10);  // Works fine
        checkNumber(-5);  // Throws exception
    }
}
Output
Number is 10 Exception in thread "main" java.lang.IllegalArgumentException: Number must be non-negative at ThrowExample.checkNumber(ThrowExample.java:4) at ThrowExample.main(ThrowExample.java:11)
⚠️

Common Pitfalls

Common mistakes when using throw include:

  • Throwing null instead of an exception object causes NullPointerException.
  • Not creating a new exception object (e.g., throw Exception; is invalid).
  • Throwing checked exceptions without declaring them in the method signature causes compile errors.
java
public class ThrowMistake {
    public static void wrongThrow() {
        // throw null; // Causes NullPointerException at runtime

        // throw Exception; // Compile error: Exception is a type, not an object

        // Correct way:
        throw new RuntimeException("Proper exception");
    }
}
📊

Quick Reference

UsageDescription
throw new ExceptionType("message");Throws a new exception with a message
throw new RuntimeException();Throws an unchecked exception
throw new IOException();Throws a checked exception (must declare)
throw null;Causes NullPointerException (avoid)

Key Takeaways

Use throw followed by an exception object to signal errors manually.
Always create a new exception instance with new when using throw.
Checked exceptions thrown must be declared in the method signature with throws.
Avoid throwing null as it causes a NullPointerException.
Use throw inside methods to enforce input validation or error conditions.