Is there a reason to do a cast when throwing an exception in Java?

exception, java

Solution

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

Problem

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?

Original source