1

I read that we need not close an resource explicitly , it will be closed by java itself, let's say if i have written a code .

try(FileInputStream fis = new FileInputStream("");){
  // code to to somethings
}

the FileInputStream will be automatically closed , if while closing it generates an error , it will suppress that expression.

So if while closing an FileInputStream an exception is thrown, since the exception will be suppressed , the resource is not closed, Will it generate a resource leak ?

Svetlin Zarev
  • 14,713
  • 4
  • 53
  • 82
Adon Smith
  • 1,849
  • 7
  • 19
  • 19
  • 1
    Note that it will only suppress the exception if an exception is thrown from the try block. The suppressed exception is still available by calling [`getSuppressed()`](http://docs.oracle.com/javase/7/docs/api/java/lang/Throwable.html#getSuppressed%28%29) on the thrown exception. – JB Nizet Jan 25 '15 at 10:40
  • See http://stackoverflow.com/questions/26459988/is-it-meaningful-for-autocloseables-close-method-to-throw-an-exception-how-sho – Raedwald Jan 25 '15 at 11:17

1 Answers1

2

So if while closing an FileInputStream an expression exception is generated, since the expression exception will be suppressed , the resource is not closed...

You don't know it isn't closed, just that you got an exception while closing it.

... Will it generate a resource leak ?

It may or may not create a leak, but there's nothing you can do about it. If you've tried to close the resource, you've done your job.

But JB Nizet makes a very important point: The exception is only suppressed if some other exception is thrown within the try block (or within a finally block attached to it). If there's no exception during the try (or finally), an exception closing the resource won't be suppressed.

Community
  • 1
  • 1
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875