Home > Mobile >  Maintaining multiple Exception types while exception chaining in single try-catch
Maintaining multiple Exception types while exception chaining in single try-catch

Time:09-15

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);
    }
}

CodePudding user response:

i don't think there simple approach if you don't like multiple catch my approach would be something like this but to me one way or the other you still have some redundance either mutiple catch or do multiple instanceof your exception.

try {
     someFunction()
} catch (Exception ex) {
     if (ex instanceof ExceptionA) {
         throw new ExceptionA("Important information here", ex);
     } else if(ex instanceof ExceptionB){
         throw new ExceptionB("Important information here", ex);
     } else {
         throw new ExceptionC("Important information here", ex);
     }
}

public class MyThrowClass {

    public static void main(String[] args) throws Exception {

        try {
            someFuntion(1);
        } catch (Throwable t) {

            throw new Exception("Important information here", t);
        }

    }

        public static void someFuntion(int value) throws ExceptionA, ExceptionB {
            if (value == 1) {
                throw new ExceptionA("Exception A");
            }
            throw new ExceptionB("Exception B");
    
        }
    }

enter image description here

  • Related