Search code examples
javajava-7try-with-resourcesresource-leak

Try with Resources: Resource leak while closing resources in TWR block


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 ?


Solution

  • 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.