1

The following code snippet ...

    try
    {
        myFile = new FileInputStream( "something.dat" );
        ...
    }
    catch ( IOExcpetion ioe ) 
    { 
        ... 
    }
    finally
    {
        try
        {
            myFile.close();
        }
        catch ( Exception e ) 
        {
            ... 
        }
    }

... is closing the file within finally, which I understand. But why is it necessary to have another try/catch block within? It seems awkward to me. Is there a way around this?

Grateful
  • 9,685
  • 10
  • 45
  • 77
  • 1
    What happens if you remove the final `try`/`catch` block, and just call `myFile.close()`? You'll see why the `try` is necessary. – Greg Hewgill Jun 17 '15 at 03:44
  • 1
    Take a look at [AutoCloseable](http://docs.oracle.com/javase/7/docs/api/java/lang/AutoCloseable.html) if you feel your current code is awkward. – Codebender Jun 17 '15 at 03:45
  • @GregHewgill Thank you for answering. But I don't think I was clear enough. I know syntactically that it is required... but it seems awkward. I wanted to know the reasons for Java having designed it this way. Secondly, I wanted to know if there was a more convenient way to write the above. – Grateful Jun 17 '15 at 03:46
  • 4
    `FileInputStream.close()` throws `IOException` therefore you need a `try-catch` around `myfile.close()` – Karthik Kalyanasundaram Jun 17 '15 at 03:47
  • @KarthikKalyanasundaram Can you kindly read my comment above. Thanks. – Grateful Jun 17 '15 at 03:48
  • 1
    Better way: use try with resources and you don't have to use a try-catch inside your finally statement – morgano Jun 17 '15 at 03:48
  • There are two possible reasons: 1. if your method doesn't throw IOException it will need to be caught. 2. if the close method then does throw an exception the catch will "eat it" rather than it being thrown and the code after the finally block wont be reached. – slipperyseal Jun 17 '15 at 03:48
  • @morgano That sounds good. Can you please provide any examples or perhaps a link to a resource that I could check online? – Grateful Jun 17 '15 at 03:49
  • 1
    @grateful, check this answer in another question: http://stackoverflow.com/a/17739460/2164109 for an example of how to transform your code using try with resources – morgano Jun 17 '15 at 03:50
  • @Grateful, Karthik's comment is good explanation. You need a `try-catch` cause `FileInputStream.close()` throws `IOException`. Where are you closing your file is completely up to you. It is not anywhere written that you must close it in `finally`. Rather, it is convenient that even if there is some exception coming in your primary `try` block, your file closes successfully. – Aakash Jun 17 '15 at 03:50
  • 1
    *"I wanted to know the reasons for Java having designed it this way.*" - Because you can do anything within the final block and Java has no idea what you might do, and what you might do might cause another exception. A final block is just another block of code, there's nothing special about it (from within the block itself). *"I wanted to know if there was a more convenient way to write the above"* - try-with-resources in Java 7+ – MadProgrammer Jun 17 '15 at 03:53
  • @morgano Wow. That is so cool. I would like you to provide this as a solution so that I can accept it. – Grateful Jun 17 '15 at 03:55
  • @Grateful no worries man, for now it is sufficient to know that I was helpful to you; you can take ankur-singhal's answer as the accepted one, and if you found my answer in the other question useful, just upvote it :-) – morgano Jun 17 '15 at 03:59
  • @morgano Thanks man. I have selected his answer with your permission. – Grateful Jun 17 '15 at 04:00
  • remember to never throw a HeatDeathOfTheUniverseException because it wont be caught. it will just sit there for all of eternity. – slipperyseal Jun 17 '15 at 04:04

2 Answers2

4

Calling close() method on FIleInputStream, has to be surrounded by try catch clause. The API method itself is throwing the IOException exception. Also IOException is the checked exception, so we need to handle this.

Checked Exception

Checked exceptions are checked at compile-time. It means if a method is throwing a checked exception then it should handle the exception using try-catch block or it should declare the exception using throws keyword, otherwise the program will give a compilation error. It is named as checked exception because these exceptions are checked at Compile time.

From the API,

/**
     * Closes this file input stream and releases any system resources
     * associated with the stream.
     *
     * <p> If this stream has an associated channel then the channel is closed
     * as well.
     *
     * @exception  IOException  if an I/O error occurs.
     *
     * @revised 1.4
     * @spec JSR-51
     */
    public void close() throws IOException {
}

Since the close(), method is throwing IOException, either you need to re-throw the same or surround the statement with try/catch.

Refer this

Also talking about Java7, conveniently you can handle the same

1.) Catching Multiple Exception

2.) The try-with-resources Statement

To understand the causes of IOException, please refer similar question here.

Community
  • 1
  • 1
Ankur Singhal
  • 26,012
  • 16
  • 82
  • 116
0

Things you need to know

finally block

This block guarantees that the code written in this block will be executed for sure after the execution of try or catch block. It executes whether the exception occurs or not.

Why to write close() in finally

Because we want to close our file irrespective of whether exception occurs or not.

Why close() needs try-catch

For this you need to know what CheckedExceptions are.

In short I would say, CheckedExceptions are those which are mandatory to handle i.e. you either need to write it with in try-catch block or declare to be thrown by throws keyword. If you see the source code of close() method you will come to know that it throws java.io.IOException which is checked exception, so you need to write this in try-catch.

gprathour
  • 14,813
  • 5
  • 66
  • 90