Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the correct way to silently close InputStream in finally block without losing the original exception?

Tags:

java

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()?

like image 671
Evgeniy Dorofeev Avatar asked Apr 23 '13 08:04

Evgeniy Dorofeev


People also ask

Which exception is thrown when the stream is closed in finally block?

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.

Which exception is thrown by FileInputStream?

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.

What happens if you don't close InputStream?

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.


1 Answers

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.

like image 157
Alpedar Avatar answered Sep 24 '22 10:09

Alpedar