Unconfirmed Java exception

While learning Java, I often stumble upon this error. This happens as follows:

Java.io.FileNotFound exception; must be caught or declared abandoned.

java.io.FileNotFound is just an example, I saw a lot of different ones. In this particular case, the error code is as follows:

OutputStream out = new BufferedOutputStream(new FileOutputStream(new File("myfile.pdf")));

The error always disappears, and the code compiles and runs successfully as soon as I put the statement inside the try / catch block. Sometimes it's good enough for me, but sometimes not.

Firstly, the examples I study do not always use try / catch and, nevertheless, should work.

More importantly, sometimes when I put all the code inside try / catch, it cannot work at all. For instance. in this particular case, I need out.close (); in finally {} ; but if the expression itself is inside try {} , finally {} does not see " out and therefore cannot close it. p>

My first idea was to import java.io.FileNotFound; or other relevant exception, but that did not help.

+3
source share
2 answers

, . Java :

InputStream in = null;
try {
  in = new InputStream(...);
  // do stuff
} catch (IOException e) {
  // do whatever
} finally {
  if (in != null) {
    try {
      in.close();
    } catch (Exception e) {
    }
  }
}

? . ? . Java 7 ARM, .

:

public void doStuff() throws IOException {
  InputStream in = new InputStream(...);
  // do stuff
  in.close();
}

close() , , finally.

, IOException. , catch it ( , ..).

+6

Java . ( , , ).

, . , , .

, :

acquire();
try {
    use();
} finally {
    release();
}

acquire() try. acquire() try ( ). finally.

, . , Java . :

try {
    final FileOutputStream rawOut = new FileOutputStream(file);
    try {
        OutputStream out = new BufferedOutputStream(rawOut);
        ...
        out.flush();
    } finally {
        rawOut.close();
    }
} catch (FileNotFoundException exc) {
    ...do something not being able to create file...
} catch (IOException exc) {
    ...handle create file but borked - oops...
}
+1

Source: https://habr.com/ru/post/1729031/


All Articles