I have a function that throws several different types of custom Exceptions. I wish to catch these exceptions from that function, add some important information, and then throw the exception as their original type to pass up the caller chain (exception chaining). I would like this to be compact in a single catch if possible.
I know Java 7+ has the functionality to handle multiple Exception types and throw them while maintaining their type. However, when exception chaining I cannot catch and throw multiple Exception types in the same catch block without losing the type. Is it possible to throw an exception maintaining its original type in a single catch block that accepts multiple Exception types? Or do I have to split it into 3 nearly-equivalent (essentially redundant) catch blocks?
Example:
void thisWorks() {
try {
someFunction(); // throws ExceptionA, ExceptionB, ExceptionC
} catch (ExceptionA | ExceptionB | ExceptionC exception) {
throw exception; // still has the original ExceptionA/ExceptionB/ExceptionC type
}
}
void whatIWant() {
try {
someFunction();
} catch (ExceptionA | ExceptionB | ExceptionC exception) {
// This throws an Exception, not the original ExceptionA/ExceptionB/ExceptionC type.
// Is it possible to fit this in a single block like the thisWorks() function?
// Or do I have to split into 3 catch blocks just for the throw type?
throw new Exception("Important information here", exception);
}
}
