Java throw Keyword

Introduction

The throw keyword in Java is used to explicitly throw an exception. This allows developers to create their own exceptions or rethrow existing exceptions, providing greater control over error handling in their programs. This blog post will explore how to use the throw keyword in Java, including syntax, examples, and common use cases.

Table of Contents

  1. What is the throw Keyword?
  2. Syntax
  3. Throwing a Built-in Exception
  4. Throwing a Custom Exception
  5. Propagating Exceptions
  6. Common Use Cases
  7. Complete Example Program
  8. Conclusion

1. What is the throw Keyword?

The throw keyword is used to explicitly throw an exception in Java. This can be used to throw both built-in exceptions and custom exceptions. When an exception is thrown, the normal flow of the program is interrupted, and control is transferred to the nearest enclosing try/catch block that can handle the exception.

2. Syntax

The syntax for the throw keyword is as follows:

throw new ExceptionType("Exception message");
  • ExceptionType is the type of the exception to be thrown.
  • "Exception message" is an optional message providing additional information about the exception.

3. Throwing a Built-in Exception

You can use the throw keyword to throw built-in exceptions such as IllegalArgumentException, NullPointerException, etc.

Example:

public class ThrowBuiltInExceptionExample {
    public static void main(String[] args) {
        try {
            validateAge(15); // This will throw an IllegalArgumentException
        } catch (IllegalArgumentException e) {
            System.out.println("Exception caught: " + e.getMessage());
        }
    }

    public static void validateAge(int age) {
        if (age < 18) {
            throw new IllegalArgumentException("Age must be 18 or older.");
        }
        System.out.println("Age is valid.");
    }
}

Output:

Exception caught: Age must be 18 or older.

Explanation:

  • The validateAge method throws an IllegalArgumentException if the age is less than 18.
  • The exception is caught in the try/catch block in the main method.

4. Throwing a Custom Exception

You can also create your own custom exceptions by extending the Exception class and then throw these custom exceptions using the throw keyword.

Example:

class InvalidAgeException extends Exception {
    public InvalidAgeException(String message) {
        super(message);
    }
}

public class ThrowCustomExceptionExample {
    public static void main(String[] args) {
        try {
            validateAge(15); // This will throw an InvalidAgeException
        } catch (InvalidAgeException e) {
            System.out.println("Exception caught: " + e.getMessage());
        }
    }

    public static void validateAge(int age) throws InvalidAgeException {
        if (age < 18) {
            throw new InvalidAgeException("Age must be 18 or older.");
        }
        System.out.println("Age is valid.");
    }
}

Output:

Exception caught: Age must be 18 or older.

Explanation:

  • The InvalidAgeException class extends the Exception class.
  • The validateAge method throws an InvalidAgeException if the age is less than 18.
  • The exception is caught in the try/catch block in the main method.

5. Propagating Exceptions

When an exception is thrown in a method, it can propagate up the call stack if not caught within the method. This means the exception can be handled by any method higher up in the call stack that has a corresponding try/catch block.

Example:

public class PropagateExceptionExample {
    public static void main(String[] args) {
        try {
            method1(); // This will propagate the exception
        } catch (Exception e) {
            System.out.println("Exception caught in main: " + e.getMessage());
        }
    }

    public static void method1() throws Exception {
        method2();
    }

    public static void method2() throws Exception {
        throw new Exception("Exception thrown in method2.");
    }
}

Output:

Exception caught in main: Exception thrown in method2.

Explanation:

  • The method2 method throws an exception.
  • The method1 method calls method2 and declares that it throws the same exception.
  • The exception is propagated up to the main method, where it is caught.

6. Common Use Cases

Validating Input

Using throw to validate input and provide meaningful error messages.

public class ValidateInputExample {
    public static void main(String[] args) {
        try {
            setUsername(null); // This will throw an IllegalArgumentException
        } catch (IllegalArgumentException e) {
            System.out.println("Exception caught: " + e.getMessage());
        }
    }

    public static void setUsername(String username) {
        if (username == null || username.isEmpty()) {
            throw new IllegalArgumentException("Username cannot be null or empty.");
        }
        System.out.println("Username is valid.");
    }
}

Handling Unexpected Conditions

Using throw to handle unexpected conditions in your code.

public class UnexpectedConditionExample {
    public static void main(String[] args) {
        try {
            divide(10, 0); // This will throw an ArithmeticException
        } catch (ArithmeticException e) {
            System.out.println("Exception caught: " + e.getMessage());
        }
    }

    public static int divide(int a, int b) {
        if (b == 0) {
            throw new ArithmeticException("Division by zero.");
        }
        return a / b;
    }
}

7. Complete Example Program

Here is a complete program that demonstrates the use of the throw keyword with both built-in and custom exceptions, as well as exception propagation.

Example Code:

class InvalidAgeException extends Exception {
    public InvalidAgeException(String message) {
        super(message);
    }
}

public class ThrowKeywordExample {
    public static void main(String[] args) {
        // Example 1: Throwing a built-in exception
        try {
            validateAgeWithBuiltInException(15);
        } catch (IllegalArgumentException e) {
            System.out.println("Caught built-in exception: " + e.getMessage());
        }

        // Example 2: Throwing a custom exception
        try {
            validateAgeWithCustomException(15);
        } catch (InvalidAgeException e) {
            System.out.println("Caught custom exception: " + e.getMessage());
        }

        // Example 3: Propagating exceptions
        try {
            method1();
        } catch (Exception e) {
            System.out.println("Exception propagated to main: " + e.getMessage());
        }
    }

    public static void validateAgeWithBuiltInException(int age) {
        if (age < 18) {
            throw new IllegalArgumentException("Age must be 18 or older.");
        }
        System.out.println("Age is valid.");
    }

    public static void validateAgeWithCustomException(int age) throws InvalidAgeException {
        if (age < 18) {
            throw new InvalidAgeException("Age must be 18 or older.");
        }
        System.out.println("Age is valid.");
    }

    public static void method1() throws Exception {
        method2();
    }

    public static void method2() throws Exception {
        throw new Exception("Exception thrown in method2.");
    }
}

Output:

Caught built-in exception: Age must be 18 or older.
Caught custom exception: Age must be 18 or older.
Exception propagated to main: Exception thrown in method2.

8. Conclusion

The throw keyword in Java is used for managing exceptions. By using throw, you can explicitly throw both built-in and custom exceptions, allowing you to handle error conditions in a controlled and meaningful way. Understanding how to use throw effectively can help you write more robust and maintainable Java code.

Happy coding!

Comments