I am wondering if the below code closes InputStream in finally block correctly
InputStream is = new FileInputStream("test"); try { for(;;) { int b = is.read(); ... } } finally { try { is.close(); } catch(IOException e) { } }
If an exception happens during is.read() will be it ignored / suppressed if an exception happens during is.close()?
Don't close in finally block The close method can throw an IOException and FileInputStream / ObjectInputStream can be null. When you use . close in finally , you must check null and try/catch again.
The FileInputStream read() method throws a java. io. IOException if for some reason it can't read from the file. Again, the InputFile class makes no attempt to catch or declare this exception.
The operating system will only allow a single process to open a certain number of files, and if you don't close your input streams, it might forbid the JVM from opening any more.
Best way is to use Java 7 and use try with resources, or do same thing manualy and add exception from closing as suppressed exception.
Pre Java 7: If you are throwing your custom exception, you can add in it supressed exception like it is done in Java 7 (in your exception create fields List suppressed and put there exceptions from close operation and when dealing with your exception, look there too. If you cannot do that, I don't know anything better than just log it.
examples: from Java tutorials
static String readFirstLineFromFile(String path) throws IOException { try (BufferedReader br = new BufferedReader(new FileReader(path))) { return br.readLine(); } }
but better form is:
static String readFirstLineFromFile(String path) throws IOException { try (FileReader fr = new FileReader(path); BufferedReader br = new BufferedReader(fr)) { return br.readLine(); } }
This way even if creation of FileReader is succesfull but creation of BufferedReader fails (eg not enough memory), FileReader will be closed.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With