Question

I recently came across an odd-to-me pattern in two completely independent bits of Java code: casting something that is already a Throwable to a more specific exception class when throwing. E.g., the following is from some Tomcat code:

Exception exception = ex.getException();
if (exception instanceof IOException) {
    throw (IOException) exception;
}

The cast to IOException seems entirely pointless to me, but having seen similar twice in the wild, I wonder if I'm missing something?

Was it helpful?

Solution

The cast tells the compiler what kind of exception it is, and therefore whether it's "checked" or "unchecked".

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top