Quantcast
Channel: Scratch Where It's Itching
Viewing all articles
Browse latest Browse all 73

Suppressed Exceptions

$
0
0
Thanks to Alexis Lopez and his blog, I discovered a new method that appeared in the Exception class in Java 7: getSuppressed(). According to the JavaDoc, this method was added because of the new try-with-resource feature. A common trap of using Java IO can be seen in the following code:
publicvoid readFile (File f) throws IOException {
    FileInputStream in = null;try {
        in = new FileInputStream(f);//read file    }finally {
        in.close();
    }
}

The problem with this code appears when you have an Exception thrown during file reading. In this case, the code will jump first to the finally block, where it will attempt to close the stream. As it is sometimes the case when there is a problem while reading the file, there is also a problem while closing it. The result will be another exception thrown, overriding the first one, which will be simply lost.

That's where the suppressed Exception becomes handy. The better way to write the code is the following:

publicvoid readFile (File f) throws IOException {
    FileInputStream in = null;
    Exception suppressed = null;try {
        in = new FileInputStream(f);//read file    }catch (IOException ex) {
        suppressed = ex;throw ex;
    }finally {try {
            in.close();
        } catch (IOException ex) {if (suppressed != null) {
                ex.addSuppressed(suppressed);
            }throw ex;
        }
    }
}
If there are several streams to close, suppressed exceptions can be stacked, although the code will become quite complicated. Better to use the try-with-resource feature.

Viewing all articles
Browse latest Browse all 73

Trending Articles