Java throw and throws

Exception handling is an essential part of Java programming, allowing developers to manage errors gracefully. While the try...catch block catches exceptions, Java provides two additional keywords — throw and throws — that play a key role in throwing and propagating exceptions. Understanding how and when to use these keywords is crucial for writing robust and maintainable code.


What is the throw Keyword?

The throw keyword in Java is used to explicitly throw an exception. It can be used inside a method or any block of code to signal an error or exceptional condition. When an exception is thrown using throw, the normal flow of execution is interrupted, and the control is transferred to the nearest exception handler (usually a catch block).

Syntax of throw:

throw new ExceptionType("Exception message");

Example: Using throw

public class ThrowExample {
    public static void main(String[] args) {
        try {
            checkAge(15);  // This will throw an exception
        } catch (IllegalArgumentException e) {
            System.out.println(e.getMessage());
        }
    }

    static void checkAge(int age) {
        if (age < 18) {
            throw new IllegalArgumentException("Age must be at least 18.");
        } else {
            System.out.println("Access granted.");
        }
    }
}

Output:

Age must be at least 18.

In this example:

  • The checkAge method throws an IllegalArgumentException if the age is less than 18.
  • The throw keyword is used to explicitly throw the exception.
  • The catch block catches the exception and prints the error message.

What is the throws Keyword?

The throws keyword in Java is used in a method declaration to indicate that the method might throw one or more exceptions during its execution. Unlike throw, which is used to explicitly throw an exception, throws is used to declare exceptions that may be thrown but are not handled within the method.

This is particularly useful for checked exceptions, which the compiler requires you to either handle or declare.

Syntax of throws:

public returnType methodName() throws ExceptionType {
    // Method code
}

Example: Using throws

public class ThrowsExample {
    public static void main(String[] args) {
        try {
            methodThatThrows();  // This will throw an exception
        } catch (Exception e) {
            System.out.println("Caught exception: " + e.getMessage());
        }
    }

    static void methodThatThrows() throws Exception {
        throw new Exception("This is a thrown exception.");
    }
}

Output:

Caught exception: This is a thrown exception.

In this example:

  • The method methodThatThrows declares that it can throw an exception using throws.
  • The main method calls methodThatThrows and catches the exception.

Difference Between throw and throws

While both throw and throws deal with exceptions, they serve different purposes:

Keyword Purpose Where it is Used Handling Mechanism
throw Used to explicitly throw an exception. Inside methods or code blocks. The exception is thrown immediately, interrupting normal execution.
throws Used to declare that a method can throw one or more exceptions. In method signatures (declaration). The exception is not handled inside the method but propagated to the caller.

Example: Using throw and throws Together

public class ThrowAndThrowsExample {
    public static void main(String[] args) {
        try {
            methodThatThrows();
        } catch (Exception e) {
            System.out.println("Caught exception: " + e.getMessage());
        }
    }

    static void methodThatThrows() throws Exception {
        throw new Exception("This is an exception thrown using throw.");
    }
}

Output:

Caught exception: This is an exception thrown using throw.

In this example:

  • The methodThatThrows method declares that it can throw an exception using throws.
  • Inside the method, the throw keyword is used to explicitly throw an exception.

Custom Exceptions with throw and throws

You can use the throw keyword to throw custom exceptions that you define yourself. To create a custom exception, you extend the Exception class (for checked exceptions) or the RuntimeException class (for unchecked exceptions).

Example: Custom Exception Using throw and throws

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

public class CustomExceptionExample {
    public static void main(String[] args) {
        try {
            validateAge(15);  // This will throw the custom exception
        } catch (InvalidAgeException e) {
            System.out.println(e.getMessage());
        }
    }

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

Output:

Age must be at least 18.

In this example:

  • A custom exception InvalidAgeException is created by extending the Exception class.
  • The validateAge method uses the throw keyword to throw the custom exception if the age is less than 18.
  • The throws keyword is used to declare that the method can throw the custom exception.

Best Practices for Using throw and throws

  1. Use throw for Immediate Exception Handling: Use the throw keyword when you need to explicitly throw an exception, either for custom error handling or to signal that something is wrong in your method.

  2. Use throws for Propagating Exceptions: Use the throws keyword when you want to declare that a method can throw an exception, allowing the calling method to handle it. This is especially useful for checked exceptions.

  3. Always Document Exceptions: Whether using throw or throws, ensure that your methods clearly document the exceptions they throw. This helps other developers understand the possible error conditions.

  4. Handle Specific Exceptions: When declaring exceptions with throws, try to be specific about the types of exceptions your method can throw. Avoid throwing generic exceptions unless necessary.

  5. Use Custom Exceptions Wisely: While Java provides many built-in exceptions, creating custom exceptions can help make your error handling more meaningful and specific to your application.