user6162628
user6162628

Reputation: 7

unreported exception IOException; must be caught or declared to be thrown

I have a question , why does java keeps throwing that exception ! Is the problem with the stream ? because I handeled all IOExceptionS !

[[jio0yh.java:12: error: unreported exception IOException; must be caught or declared to be thrown]]>>

That's the exception that I'm getting!

here is my code

import java.io.*;
public class jio0yh{

    public static void main(String[]args){

       FileInputStream OD=null;

       try{

 
           File f=new File("Binary.dat");
 
           OD= new FileInputStream(f);
 
           byte[]b=new byte[(int)f.length()];

           OD.read(b);

           for(int i=0;i<b.length;i++)

              System.out.println(b[i]);
       } catch(FileNotFoundException e){
           System.out.println(e.getMessage());
       } catch(IOException e){
           System.out.println(e.getMessage());
           OD.close();
       }

    }
}

Upvotes: 0

Views: 2175

Answers (1)

Adam Yin
Adam Yin

Reputation: 11

The OD.close(); in your IOException catch block is also susceptible to throwing another IOException.

You should surround the final OD.close() in a finally block:

// ... Any previous try catch code
} finally {
    if (OD != null) {
        try {
            OD.close();
        } catch (IOException e) {
            // ignore ... any significant errors should already have been
            // reported via an IOException from the final flush.
        }
    }
}

Refer to the following for a more thorough explanation:

Java try/catch/finally best practices while acquiring/closing resources

Upvotes: 1

Related Questions