Suppressed Exceptions – She is the central protagonist, but she isn’t the only one.
Today feels a little different; I feel like I should be on the beach, marveling at the wonders of creation. On the other hand, it’s Monday morning, and I’ve got a few hundred error logs to go through as part of my routine to get the day started. While I was playing my game, I noticed this line, which does not make sense; I know my code by heart, line by line, but this one appears strange.
She’s always told me I’m the only one, but today appears to be the one day I’m sober enough to notice there’s another one lurking in the shadows.
This is the story of suppressed exceptions and how they can deceive you, tricking you into thinking you’ve caught up just to discover you’ve been duped.
When multiple exceptions are thrown, all but the first are called suppressed exceptions. The first exception is the primary exception which is caught by the catch block. keep in mind that suppressed only apply to exceptions thrown in the try clause.
If more than two resources throw an exception, the first one to be thrown becomes the primary exception, with the rest being grouped as suppressed exceptions. And since resources are closed in reverse order in which they are declared, the primary exception would be on the last declared resource that throws an exception.
import java.io.FileNotFoundException;
/**
* @author - LeeN
* PROJECT NAME: JDBCTESTS
* CREATED ON: Monday 14 February 2022 - 6:21 AM
*/
public class SuppressedExpression implements AutoCloseable {
@Override
public void close() throws Exception {
throw new IllegalStateException("The program has jammed");
}
public static void main(String[] args) throws Exception {
try(SuppressedExpression sp = new SuppressedExpression()){
throw new FileNotFoundException("Primary exception: FileNotFound");
}catch (FileNotFoundException e){
System.out.println("Primary exception: " + e.getMessage());
for (Throwable t: e.getSuppressed()){
System.out.println("Suppressed Exception: " + e.getMessage());
}
}
}
}
I had some code in my production code that was reading and writing files. The issue I had was that some exceptions were caught in the catch block while others were caught in the finally block; this is bad practice and should never occur where try-with-resources is used.