throw and throws in Java

These are two related but distinct concepts in Java's exception handling mechanism. throw keyword Used to explicitly throw an exception from a method or block of code You can throw either checked or unchecked exceptions Syntax: throw new ExceptionType("message"); Example: public void checkAge(int age) { if (age

May 8, 2025 - 15:35
 0
throw and throws in Java

These are two related but distinct concepts in Java's exception handling mechanism.

throw keyword

  • Used to explicitly throw an exception from a method or block of code
  • You can throw either checked or unchecked exceptions
  • Syntax: throw new ExceptionType("message");

Example:

public void checkAge(int age) {
    if (age < 18) {
        throw new ArithmeticException("Access denied - You must be at least 18 years old.");
    }
    System.out.println("Access granted");
}

throws keyword

  • Used in method signature to declare that a method might throw one or more exceptions
  • Primarily used for checked exceptions (though you can use it for unchecked exceptions too)
  • Caller of the method must handle or declare these exceptions
  • Syntax: returnType methodName() throws Exception1, Exception2 {...}

Example:

public void readFile() throws FileNotFoundException, IOException {
    // code that might throw these exceptions
}

Key Differences

Feature throw throws
Purpose To explicitly throw an exception To declare possible exceptions
Location Inside method body In method signature
Exceptions Can throw one exception at a time Can declare multiple exceptions
Type Statement Clause

Combined Example

public class Example {
    // Method declares it might throw IOException
    public void processFile(String filePath) throws IOException {
        if (filePath == null) {
            // Explicitly throwing an exception
            throw new IllegalArgumentException("File path cannot be null");
        }

        // Code that might throw IOException
        FileReader file = new FileReader(filePath);
        // ... more code
    }
}

Remember:

  • Use throw when you want to generate an exception
  • Use throws when your method might propagate an exception that it doesn't handle