Java Throws Keyword

Naveen AnamaneniUpdated · 3 min read

A low-level method that reads a file often can't sensibly handle a missing file: it doesn't know whether to ask the user, use a default, or give up. Its caller knows. The throws clause in a method's header says, "this method may throw these checked exceptions; whoever calls me must deal with them." It's a promise written into the method's signature, and the compiler holds every caller to it.

Passing Responsibility Up

Report.java▶ Try it
import java.io.FileNotFoundException;
import java.io.FileReader;
 
public class Report {
    static FileReader openMarks(String file) throws FileNotFoundException {
        System.out.println("opening " + file);
        return new FileReader(file);
    }
 
    static void printReport(String file) throws FileNotFoundException {
        openMarks(file);
        System.out.println("report printed");
    }
 
    public static void main(String[] args) {
        try {
            printReport("advitha-marks.txt");
        } catch (FileNotFoundException e) {
            System.out.println("No marks file yet, showing an empty report");
        }
    }
}
Output
opening advitha-marks.txt
No marks file yet, showing an empty report

How it works

  1. openMarks declares throws FileNotFoundException: it doesn't catch the problem, it passes it on.
  2. printReport calls openMarks, so it must also catch or declare. It declares too, passing the problem further up.
  3. main is the place that knows what to do (show an empty report), so it catches it.

Catch or Declare?

Catch it when...Declare it when...
This method can do something useful: retry, use a default, show a messageOnly the caller knows how to respond
The exception is an internal detail callers shouldn't seeThe exception is part of the method's contract

Rules of throws

RuleExample
List several types with commasvoid save() throws IOException, SQLException
A parent type covers its childrenthrows IOException also covers FileNotFoundException
Unchecked exceptions may be listed, but don't have to bethrows IllegalArgumentException documents it
main can declare toopublic static void main(String[] args) throws IOException: the JVM prints the stack trace if it escapes
Overriding methods can't declare broader checked exceptionsSee "Exception Handling with Method Overriding"

Common Mistakes

throws Exception on every method. It hides real information and forces callers to catch everything.

Declaring and never handling anywhere. Somebody, eventually main, must decide what to do.

Thinking throws throws something. It only declares; throw actually throws.

Interview Corner

What is the throws keyword used for?

throws appears in a method or constructor declaration to list the checked exceptions it may propagate instead of handling. Callers must then catch those exceptions or declare them in turn. It can also list unchecked exceptions for documentation, although that isn't required.

Practice

  1. Easy: Write static void pause(long ms) throws InterruptedException that calls Thread.sleep(ms), and call it from main with a try-catch.
  2. Harder: Add a third level to Report.java between printReport and main. Which methods need throws, and which one catches?

Quick check: throws

4 questions
1Where is throws written?
2A method calls one that declares a checked exception. What must it do?
3Does throws IOException cover FileNotFoundException?
4Must unchecked exceptions be declared with throws?

Key Takeaways

Was this tutorial helpful?

Lesson 227 of 482