2
class Demo
{
    public static void main(String args[]) throws java.io.IOException
    {
        try(FileInputStream fin = new FileInputStream("Demo.txt"))
        {
            //This block is executed successfully
        }
        
        System.out.println("Will it be executed if error occurs in try clause");
    }
}

Suppose that the code in try block is executed successfully as mentioned in the code, and some exception occurs in try with resource clause, that means exception occurs in auto closing of file.

How that exception in the try with resource clause will be handled?

What I want to ask is that will that exception be thrown to JVM and will terminate my program abruptly and the println statement will not be executed?

Can I catch that exception so that remaining program can also be executed?

Community
  • 1
  • 1
kevin gomes
  • 1,775
  • 5
  • 22
  • 30

4 Answers4

6

If an exception is thrown by the close method of an AutoClosable it will indeed be thrown after the try block has been executed.

If you need to handle the exception you can simply add a catch clause to your try clause.

The following code illustrates the behavior:

public class Foo {

    public static class Bar implements AutoCloseable {

        @Override
        public void close() {
            throw new RuntimeException();
        }

    }

    public static void main(String args[]) {
        try (Bar b = new Bar()) {
            // This block is executed successfully
        }

        System.out.println("Will it be executed if error occurs in try clause");
    }
}

It terminates the JVM with the stack trace:

Exception in thread "main" java.lang.RuntimeException
at test3.Foo$Bar.close(Foo.java:14)
at test3.Foo.main(Foo.java:25)

25 is the line where the closing } for my try clause is.

It could be handled by using:

try (Bar b = new Bar()) {
    // This block is executed successfully
} catch (Exception e) {
     // ...
}
K Erlandsson
  • 13,408
  • 6
  • 51
  • 67
4

only add catch clause, to catch the exception otherwise program will be terminated

public static void main(String[] args) throws FileNotFoundException, IOException {
        try(FileInputStream fin = new FileInputStream("Demo.txt"))
        {
            //This block is executed successfully
        }
        catch(Exception e)
        {
            e.printStackTrace();
        }
        System.out.println("Will it be executed if error occurs in try clause");
    }
Safwan Hijazi
  • 2,089
  • 2
  • 17
  • 29
1

I think with a finally the rest of the program will be run, please try it and report.

class Demo

{
    public static void main(String args[]) throws java.io.IOException
    {
        try(FileInputStream fin = new FileInputStream("Demo.txt"))
        {
            //This block is executed successfully
        } finally {
           System.out.println("Will it be executed if error occurs in try clause");
        }
    }
}
Valentin Ruano
  • 2,726
  • 19
  • 29
  • yes it work. And I have already guessed this idea. But if the code after `try block` is huge then putting a huge code in `finally block` is not appreciable. – kevin gomes Jun 21 '15 at 19:51
  • You should be careful with `finally`-blocks. `finally` is always executed, [which can lead to funny behaviours](http://stackoverflow.com/questions/65035/does-finally-always-execute-in-java). `finally` should be use for some cleanup, that needs to be done and using it for another purpose may lead to unwanted results. – Turing85 Jun 21 '15 at 19:52
  • @kevingomes you can always extract the code into its own method. – Valentin Ruano Jun 21 '15 at 19:54
  • @Turing85, I have to agree with you in part, in a more complex example a specific catch is advisable in order to do a more specific treatment to the problem, for the current example I think the finally suffices though. Don't understand the "funny" part of "funny behaviours", finally's behaviour is quite robust even if it might not be appropriate for the situation. Can you elaborate? – Valentin Ruano Jun 21 '15 at 20:08
  • @ValentinRuano [look at this](http://stackoverflow.com/questions/2309964/multiple-returns-which-one-sets-the-final-return-value) or [this](http://stackoverflow.com/a/65362/4216641). – Turing85 Jun 22 '15 at 02:33
  • @Turing85, still don't see it what the "funny" behaviour is. It is well defined in the language spec; returns or throws in the finally override the result of the try bloc. My understanding of funny behavior is for example the unpredictable effect of accessing a non-thread safe collection from different threads simultaneously. – Valentin Ruano Jun 22 '15 at 02:39
  • @ValentinRuano I did not say that is is not well-defined, only "funny" in the sense of "unexpected" or "not blatantly obvious". – Turing85 Jun 22 '15 at 02:39
1

Just delete the file Demo.txt and run the following code.

The simplest way to throw such exception is to run this code, with no existing resource (Demo.txt in this case):

public static void main(String args[])
    {
        try(FileInputStream fin = new FileInputStream("Demo.txt"))
        {

        } catch(IOException exc) {
            System.out.println("An exception has occured. Possibly, the file does not exist. " + exc);
        }

        System.out.println("Will it be executed if error occurs in try clause");
    }
mmalik
  • 185
  • 2
  • 11