throw vs throws

⭐ Interview Importance: MEDIUM
⏱️ Revision Time: 5 min

TL;DR

  • throw (Singular): Used inside the method body to actually throw an instance of an exception.
  • throws (Plural): Used in the method signature to declare that this method might throw an exception, forcing the caller to handle it.

Concept

throw

When a specific error condition occurs in your business logic, you instantiate an exception object and use the throw keyword to hand it to the JVM. The current method stops executing immediately.

throws

If a method contains code that throws a Checked Exception, but the method does not want to catch it internally, the method must append throws ExceptionName to its declaration. This acts as a warning label to any other method that wants to call it: “Warning: If you call me, I might throw this exception, so you better be prepared to handle it!”

Examples

import java.io.IOException;

public class ThrowVsThrows {
    
    // 1. 'throws' is used in the method signature (Warning label)
    public static void validateAge(int age) throws IOException {
        
        if (age < 18) {
            // 2. 'throw' is used to actually trigger the exception
            throw new IOException("Age must be 18 or older.");
        }
        
        System.out.println("Access granted.");
    }

    public static void main(String[] args) {
        
        // Because validateAge uses 'throws IOException' (a checked exception),
        // we are FORCED by the compiler to wrap the call in a try-catch here.
        try {
            validateAge(16);
        } catch (IOException e) {
            System.out.println("Error: " + e.getMessage());
        }
    }
}

Interview Questions

Q: Can you use throws with unchecked exceptions (RuntimeException)?
A: Yes, you can write public void myMethod() throws NullPointerException. However, it is entirely optional and generally discouraged. Since unchecked exceptions don’t require the caller to handle them, adding them to the throws clause is just informational documentation; the compiler will not enforce handling.

Q: Can a method declare multiple exceptions in its throws clause?
A: Yes, a method can declare multiple exceptions by separating them with commas. For example: public void processFile() throws IOException, SQLException, ParseException.