0
0
JavaHow-ToBeginner · 3 min read

How to Use Throws Keyword in Java: Syntax and Examples

In Java, the throws keyword is used in a method signature to declare that the method might throw one or more checked exceptions. It tells the caller of the method to handle or further declare these exceptions. This helps manage error handling clearly and safely.
📐

Syntax

The throws keyword is placed after the method's parameter list and before the method body. It lists one or more exception classes separated by commas.

  • Method signature: Declares the exceptions the method can throw.
  • Exception classes: Must be checked exceptions or their subclasses.
  • Caller responsibility: The caller must handle or declare these exceptions.
java
public void methodName() throws IOException, SQLException {
    // method code that might throw IOException or SQLException
}
💻

Example

This example shows a method that reads a file and declares it throws IOException. The caller handles the exception with a try-catch block.

java
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

public class ThrowsExample {
    public static void readFile(String filePath) throws IOException {
        BufferedReader reader = new BufferedReader(new FileReader(filePath));
        String line = reader.readLine();
        System.out.println("First line: " + line);
        reader.close();
    }

    public static void main(String[] args) {
        try {
            readFile("test.txt");
        } catch (IOException e) {
            System.out.println("Error reading file: " + e.getMessage());
        }
    }
}
Output
First line: Hello, world!
⚠️

Common Pitfalls

Common mistakes when using throws include:

  • Declaring unchecked exceptions (like NullPointerException) with throws, which is unnecessary.
  • Not handling or declaring checked exceptions, causing compile errors.
  • Confusing throws (declaration) with throw (actual exception throwing).
java
public void wrongMethod() throws NullPointerException { // unnecessary declaration
    throw new NullPointerException();
}

// Correct way: no throws needed for unchecked exceptions
public void correctMethod() {
    throw new NullPointerException();
}
📊

Quick Reference

Remember these tips when using throws:

  • Use throws only for checked exceptions.
  • List multiple exceptions separated by commas.
  • The caller must handle or declare the exceptions.
  • throw is used to actually throw an exception.

Key Takeaways

Use throws in method signatures to declare checked exceptions the method can throw.
The caller of the method must handle or declare these exceptions to avoid compile errors.
throws lists exceptions after the method parameters, separated by commas.
Do not declare unchecked exceptions with throws; it is optional and usually omitted.
throw is different and used to actually throw an exception inside a method.