Why am I getting "must be caught or declared to be thrown" on my program?

Java checks exception specifications at compile time. You must either catch the exception or declare it thrown in your method signature. Here's how you would declare that it may be thrown from your method:

   public void read (String [] args) throws java.io.IOException {

Catch the exception if your method needs to do something in response. Declare it as thrown if your caller needs to know about the failure.

These are not mutually exclusive. Sometimes it is useful to catch the exception, do something and re-throw the exception or a new exception that wraps the original (the "cause").

RuntimeException and its subclasses do not need to be declared.


When you work with I/O in Java most of the time you have to handle IOException which can occur any time when you read/write or even close the stream.

You have to put your sensitive block in a try//catch block and handle the exception here.

For example:

try{
    // All your I/O operations
}
catch(IOException ioe){
    //Handle exception here, most of the time you will just log it.
}

Resources:

  • oracle.com - Lesson: Exceptions