← Back to Home

throw Keyword

The throw keyword in Java is used to explicitly create and pass an exception object to the JVM. It allows developers to signal exceptional conditions manually, based on business rules or validation logic. This is a high-frequency interview topic, often confused with throws.

What Is the throw Keyword?

  • Used to explicitly throw an exception
  • Can throw one exception at a time
  • Works with exception objects
  • Transfers control to the nearest matching catch block
throw new ExceptionType("message");
          

Why throw Is Needed

  • Enforce business rules
  • Validate input explicitly
  • Create custom error conditions
  • Stop normal execution when rules are violated

Basic Syntax

throw new ArithmeticException("Invalid operation");
          

Simple Example

void checkAge(int age) {
    if (age < 18) {
        throw new ArithmeticException("Not eligible to vote");
    }
    System.out.println("Eligible to vote");
}
          

✔ Exception raised manually
✔ Control shifts to caller or catch block

Using throw with try-catch

try {
    throw new NullPointerException("Null value");
} catch (NullPointerException e) {
    System.out.println(e.getMessage());
}
          

Output:

Null value
          

throw with Checked Exceptions (Important)

When throwing a checked exception, you must handle or declare it.

void readFile() throws IOException {
    throw new IOException("File not found");
}
          

✔ Must use throws
✔ Compiler enforces handling

throw with Unchecked Exceptions

void divide(int a, int b) {
    if (b == 0) {
        throw new ArithmeticException("Division by zero");
    }
}
          

✔ No throws required
✔ Runtime exception

throw vs throws (Interview Favorite)

Aspect throw throws
Purpose Throws an exception Declares possible exceptions
Used in Method body Method signature
Exceptions One at a time Multiple allowed
Object creation Yes No
Role Cause exception Inform caller

Throwing Custom Exceptions (Preview)

class InvalidAgeException extends Exception {
    InvalidAgeException(String msg) {
        super(msg);
    }
}

throw new InvalidAgeException("Age must be >= 18");
          

✔ Enables domain-specific error handling

Important Rules of throw (Interview-Oriented)

  1. Only Throwable objects can be thrown
  2. Cannot throw multiple exceptions at once
  3. Execution stops immediately after throw
  4. Code after throw is unreachable
throw new Exception();
// System.out.println("Hello"); // ❌ unreachable
          

Common Beginner Mistakes

  • Confusing throw with throws
  • Throwing checked exception without declaring
  • Using throw for normal flow control
  • Throwing generic Exception unnecessarily
  • Forgetting meaningful error messages

Best Practices

  • Throw specific exceptions
  • Use unchecked exceptions for programming errors
  • Use checked exceptions for recoverable conditions
  • Include clear, meaningful messages
  • Avoid throwing Exception or Throwable directly

Interview-Ready Answers

Short Answer

The throw keyword is used to explicitly throw an exception object in Java.

Detailed Answer

In Java, the throw keyword allows developers to manually create and throw an exception based on specific conditions. It is used inside method bodies and transfers control to the nearest matching catch block or caller. Checked exceptions thrown using throw must be declared using throws.

throw Keyword Examples (Interview-Friendly)

1. Basic throw with Unchecked Exception

class Demo {
    public static void main(String[] args) {
        throw new ArithmeticException("Invalid operation");
    }
}
          

Output

Exception in thread "main" java.lang.ArithmeticException: Invalid operation
          

2. throw Inside Method

class Demo {
    static void validate(int age) {
        if (age < 18) {
            throw new ArithmeticException("Not eligible");
        }
        System.out.println("Eligible");
    }

    public static void main(String[] args) {
        validate(15);
    }
}
          

Output

Exception in thread "main" java.lang.ArithmeticException: Not eligible
          

3. throw with Checked Exception (Must Declare)

import java.io.IOException;

class Demo {
    static void read() throws IOException {
        throw new IOException("IO problem");
    }

    public static void main(String[] args) throws IOException {
        read();
    }
}
          

Explanation

Checked exception requires throws.

4. Handling Thrown Checked Exception

import java.io.IOException;

class Demo {
    static void read() throws IOException {
        throw new IOException("File error");
    }

    public static void main(String[] args) {
        try {
            read();
        } catch (IOException e) {
            System.out.println("Handled");
        }
    }
}
          

Output

Handled
          

5. throw with Custom Checked Exception

class InvalidAgeException extends Exception {
    InvalidAgeException(String msg) {
        super(msg);
    }
}

class Demo {
    static void check(int age) throws InvalidAgeException {
        if (age < 18) {
            throw new InvalidAgeException("Under age");
        }
    }

    public static void main(String[] args) throws InvalidAgeException {
        check(16);
    }
}
          

6. throw with Custom Unchecked Exception

class InvalidAmountException extends RuntimeException {
    InvalidAmountException(String msg) {
        super(msg);
    }
}

class Demo {
    static void pay(int amt) {
        if (amt <= 0) {
            throw new InvalidAmountException("Invalid amount");
        }
    }

    public static void main(String[] args) {
        pay(-10);
    }
}
          

7. throw Inside catch (Rethrowing)

class Demo {
    static void test() {
        try {
            int a = 10 / 0;
        } catch (ArithmeticException e) {
            System.out.println("Caught");
            throw e;
        }
    }

    public static void main(String[] args) {
        try {
            test();
        } catch (Exception e) {
            System.out.println("Rethrown");
        }
    }
}
          

Output

Caught
Rethrown
          

8. Converting Checked to Unchecked Using throw

import java.io.IOException;

class Demo {
    static void test() {
        try {
            throw new IOException();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public static void main(String[] args) {
        test();
    }
}
          

Explanation

Common practice in frameworks.

9. throw in Constructor

class Demo {
    Demo(int x) {
        if (x < 0) {
            throw new IllegalArgumentException("Negative value");
        }
    }

    public static void main(String[] args) {
        new Demo(-5);
    }
}
          

10. throw with Method Return Type

class Demo {
    static int divide(int a, int b) {
        if (b == 0) {
            throw new ArithmeticException("Divide by zero");
        }
        return a / b;
    }

    public static void main(String[] args) {
        divide(10, 0);
    }
}
          

11. throw vs throws (Side-by-Side)

class Demo {
    static void m1() throws Exception {
        throw new Exception();
    }

    static void m2() {
        throw new RuntimeException();
    }
}
          

Explanation

throw → creates exception

throws → declares exception

12. throw in Overridden Method (Checked Rule)

import java.io.IOException;

class A {
    void show() throws IOException {}
}

class B extends A {
    // void show() throws Exception {} // ❌ not allowed
}
          

Explanation

Cannot widen checked exception.

13. throw in Overridden Method (Unchecked Allowed)

class A {
    void show() {}
}

class B extends A {
    void show() {
        throw new RuntimeException();
    }
}
          

14. throw in Lambda Expression

interface Calc {
    int div(int a, int b);
}

class Demo {
    public static void main(String[] args) {
        Calc c = (a, b) -> {
            if (b == 0) throw new ArithmeticException();
            return a / b;
        };
        c.div(10, 0);
    }
}
          

15. throw with finally (Finally Executes First)

class Demo {
    static void test() {
        try {
            throw new RuntimeException();
        } finally {
            System.out.println("Finally");
        }
    }

    public static void main(String[] args) {
        test();
    }
}
          

Output

Finally
Exception in thread "main" java.lang.RuntimeException
          

16. throw in finally Overrides Exception

class Demo {
    static void test() {
        try {
            throw new ArithmeticException();
        } finally {
            throw new NullPointerException();
        }
    }

    public static void main(String[] args) {
        test();
    }
}
          

Explanation

Exception from finally dominates.

17. Conditional throw (Validation Pattern)

class Demo {
    static void login(String user) {
        if (!"admin".equals(user)) {
            throw new SecurityException("Access denied");
        }
        System.out.println("Access granted");
    }

    public static void main(String[] args) {
        login("guest");
    }
}
          

18. throw and Method Propagation

class Demo {
    static void m1() {
        throw new RuntimeException("Error");
    }

    public static void main(String[] args) {
        try {
            m1();
        } catch (RuntimeException e) {
            System.out.println(e.getMessage());
        }
    }
}
          

Output

Error
          

19. Common Interview Trap

class Demo {
    static void test() {
        throw new RuntimeException();
        // System.out.println("After"); // ❌ unreachable
    }
}
          

Explanation

Code after throw is unreachable.

20. Interview Summary – throw Keyword

class Demo {
    static void check(int x) {
        if (x < 0) {
            throw new IllegalArgumentException("Invalid");
        }
        System.out.println("Valid");
    }

    public static void main(String[] args) {
        check(-1);
    }
}
          

Key Points

  • Explicitly throws exception
  • Used for validation & custom errors
  • Works with checked & unchecked exceptions
  • Common in frameworks & APIs

Key Takeaway

throw creates the problem; throws declares the responsibility. Use throw to enforce rules and signal failures explicitly and clearly.