Handling exceptions with RandomAccessFile and FileChannel.write
<p>(I am new to java and am getting my bearings right, so please bear with the basic nature of my questions.)</p>

<p>I am looking at some open source code which has a function like this:</p>

<pre><code>private void writeFile(File jDir) throws Exception {
    File fn = new File(jDir, "abcdef.txt");

    FileChannel fc = new RandomAccessFile(fn, "rw").getChannel(); // R.A.F. leak here

    ByteBuffer zeros = ByteBuffer.allocate(512);
    fc.write(zeros, 4*1024*1024);
    fc.position(0);

    for (int i = 1; i &lt;= 10; i++) {
        fc.write(ByteBuffer.wrap("JunkJunkJunk".getBytes()));
    }
}
</code></pre>

<p>Now when I load the project in eclipse, there is a leak warning. The following fixes that warning:</p>

<pre><code>private void writeFile(File jDir) throws Exception {
    File fn = new File(jDir, "abcdef.txt");

    RandomAccessFile raf = new RandomAccessFile(fn, "rw"); // get the raf created
    FileChannel fc = raf.getChannel();

    ByteBuffer zeros = ByteBuffer.allocate(512);
    fc.write(zeros, 4*1024*1024);
    fc.position(0);

    for (int i = 1; i &lt;= 10; i++) {
        fc.write(ByteBuffer.wrap("ABCDEFGHIJKL".getBytes()));
    }

    fc.close();
    raf.close();
}
</code></pre>

<p>But I think the above is also not complete and I need to enclose the relevant code in try-catch blocks and release <code>raf</code> and <code>fc</code> in the <code>finally</code> block. Is my understanding correct ? Many implementations and examples found online do not do this, so I am not sure what the right thing to do is here.</p>