Note that there are some explanatory texts on larger screens.

plurals
  1. POIs this a safe way to release resources in Java?
    primarykey
    data
    text
    <p>Usually when code needs some resource that needs to be released I see it done like this:</p> <pre><code>InputStream in = null; try{ in = new FileInputStream("myfile.txt"); doSomethingWithStream(in); }finally{ if(in != null){ in.close(); } } </code></pre> <p>What I don't like is that you have to initialize the variable to null and after that set it to another value and in the finally block check if the resource was initialized by checking if it is null. If it is not null, it needs to be released. I know I'm nitpicking, but I feel like this could be done cleaner.</p> <p>What I would like to do is this:</p> <pre><code>InputStream in = new FileInputStream("myfile.txt"); try{ doSomethingWithStream(in); }finally{ in.close(); } </code></pre> <p>To my eyes this looks almost as safe as the previous one. If resource initialization fails and it throws an exception, there's nothing to be done(since I didn't get the resource) so it doesn't have to be inside the try block. The only thing I'm worried is if there is some way(I'm not Java certified) that an exception or error can be thrown between operations?</p> <p>Even simpler example: </p> <pre><code>Inputstream in = new FileInputStream("myfile.txt"); in.close(); </code></pre> <p>Is there any way the stream would be left open that a try-finally block would prevent?</p> <p><strong>Edit:</strong></p> <p>Maybe I should have left out the last example because it confuses everyone. This is not supposed to be a beginner level question. I know what try-finally does and I know that it is not safe if there was doSomethingWithStream in the middle in the last example. That is why it is not there. I accepted Eyals answer because it was precisely what I was looking for. There is a way to cause an exception between two operations, which would make the middle example unsafe(using Thread.stop), but since it is made using deprecated call and can mess you up no matter what you do so I feel safe using the middle example.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload