Reputation: 5417
The following program for file I/O is taken from the standard Oracle docs:
//Copy xanadu.txt byte by byte into another file
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
public class CopyBytes
{
public static void main(String[] args) //throws IOException
{
FileInputStream in = null;
FileOutputStream out = null;
try
{
in = new FileInputStream("xanadu.txt");
out = new FileOutputStream("xanadu_copy.txt");
int c;
while((c = in.read()) != -1)
{
out.write(c);
}
}
catch (IOException e)
{
System.out.println("IO exception : " + e.getMessage());
}
finally
{
if (in != null)
{
in.close();
}
if (out != null)
{
out.close();
}
}
}
}
As you can see, I commented out the throws IOException
part, thinking that since I'm catching it in the code, all should be fine. But I'm getting a compiler error:
CopyBytes.java:32: error: unreported exception IOException; must be caught or declared to be thrown
in.close();
^
CopyBytes.java:36: error: unreported exception IOException; must be caught or declared to be thrown
out.close();
^
2 errors
The errors vanish when I include the throws IOException
part, but I'm confused. Isn't it enough that I'm catching the exceptions?
Upvotes: 2
Views: 415
Reputation: 8358
In your finally block you are using in.close()
statement to close the stream. This statement also throws IOException
.
You can avoid this exception by adding try/catch
block to these close statements.
Upvotes: 4
Reputation: 726539
In order to not have to report an exception you need to put it in the try
portion of the try/catch/finally
block. Exceptions thrown in the catch
and finally
parts are not caught, prompting the compiler error:
try {
... // Exceptions thrown from here will be caught
} catch (ExceptionOne e1) {
.. // Exceptions thrown from here need to be declared
} catch (ExceptionTwo e2) {
.. // Exceptions thrown from here need to be declared
} finally {
.. // Exceptions thrown from here need to be declared
}
Upvotes: 3
Reputation: 393801
You are not catching the potential IOException that might be thrown in your finally block.
You can fix it by adding try-catch to the finally block:
finally
{
try {
if (in != null)
{
in.close();
}
if (out != null)
{
out.close();
}
}
catch (IOException ex) {
}
}
Upvotes: 6