Note that there are some explanatory texts on larger screens.

plurals
  1. POAccessing a file object outside a try/catch block that creates it (Java)
    text
    copied!<p>I want to create a RandomAccessFile object (in Java) and both write to it and read to it. My problem is that, as far I know I seem to need to create the file within a try/catch block. If I try to create it outside a try/catch block and then initialize it within the block like this, </p> <pre><code>RandomAccessFile valueFile; try { valueFile = new RandomAccessFile("valuefile.txt", "rw"); for (int i=0; i&lt;numOfNums; i++) valueFile.writeDouble(randomizer.nextDouble()*200); } catch (Exception e) { System.out.println("Couldn't find the values file."); System.exit(0); } for (int i=0; i&lt;numOfNums; i++) { double total = 0; valueFile.seek(0); // go to beginning of file to start reading it. } </code></pre> <p>then I get the error "unreported exception java.io.IOException; must be caught or declared to be thrown". (I also get "variable valueFile might not have been initialized".)</p> <p>But when I <em>do</em> create it within try/catch, like this,</p> <pre><code>try { RandomAccessFile valueFile = new RandomAccessFile("valuefile.txt", "rw"); for (int i=0; i&lt;numOfNums; i++) valueFile.writeDouble(randomizer.nextDouble()*200); } catch (Exception e) { System.out.println("Couldn't find the values file."); System.exit(0); } for (int i=0; i&lt;numOfNums; i++) { double total = 0; valueFile.seek(0); } </code></pre> <p>I get "cannot find symbol: variable valueFile" on the later part of the program. I presume that that's because valueFile is considered local to the try/catch block? But then how do I create valueFile so it's <em>not</em> local to the try/catch block?</p>
 

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