Java-Explicitly Throw IOException

Explicitly Throw IOException

In the following program, the main( ) method declares that it throws IOException and therefore we need not use try……….catch statements. I/O exceptions explicitly thrown out of main( ), this method likely to generate exceptions types of I/O exceptions. Instead of handling this object by itself, this method instructs its caller(JVM) to handle this object.

Program

final

In the following program, uses the try/catch blocks that handle the I/O errors that might occur. I/O operation is monitored for exceptions, and if an exception occurs, it is handled. Although the previous example closes the file stream after the file is read, there is a variation that is often useful. The variation is to call close( ) within a finally block. In this approach, all of the methods that access the file are contained within a try block, and the finally block is used to close the file. This way, no matter how the try block terminates, the file is closed. Because, the JVM ensures that the statements placed in the finally block are executed whether or not an exception occurs. So, even if no exception occurs during the execution of a try block, the finally block is executed. When an exception occurs, an appropriate catch block will be executed. Then, the finally block will also be executed. One advantage to this approach in general is that if the code that accesses a file terminates because of some non-I/O related exception, the file is still closed by the finally block.

Program

4

Leave a Comment