Search code examples
javainputstreamtry-with-resources

Java try with resource inputstream null check


Can somebody help on try with resource in java

try(InputStream inputStream = new FileInputStream(new File(some file)))
{
     if(inputStream == null)       //Line 3
     {
      }
}
catch(IOException e)
{
}

I want to know, is it necessary to check null on line 3. Will there be any situation or circumstances where inputStream can be null at line 3 ?


Solution

  • Given your code, no:

    InputStream inputStream = new FileInputStream(new File(some file)) will be executed before the contents of the try block. Either it will succeed, so inputStream will not be null, or it will fail, throwing an exception in the process, so the contents of the try block will never be executed.