Exception handling flow of execution

Viewed 101

I should know this, but for some reason I can't figure it out right now.

Is there a way to rewrite this code to avoid instanceof?

try {
    //Exceptions may happen
} catch (Exception1 exception1) {
    //do stuff only in case of Exception1
} catch(Exception e) {
    // do stuff in all exception cases except Exception1
    if (e instanceof Exception2) {
        // do stuff only in case of Exception2
    }
}
4 Answers

If you're going to have your exception handling for Exception inline, and don't want to repeat it, then the only solution is the OP solution.

However, if you can put the common exception handling into a function, then this would be neat:

try {
    //Exceptions may happen
} catch (Exception1 exception1) {
    //do stuff only in case of Exception1
} catch(Exception2 e) {
    doCommonStuff();
    doException2Stuff();
} catch(Exception e) {
    doCommonStuff();
}

However, the above may lead to a small problem in terms of whether you want to pass control to outside of the try/catch block, or whether you're hoping to return a value, or even throw another exception.

You may find that although all paths of your code DO throw an exception, that the above construct, of using common exception handler methods, may look to the compiler like some control paths don't.

You can, therefore, express a common exception handler, that always throws an exception like this:

private <T> T throwLastException(Exception2 input) {
   // blah blah blah
   throw new SomeException();
}

and this can be called as part of a return statement that appears to guarantee the calling function returns a value, when in fact it's just telling the compiler not to worry :)

Without any further context IMO the following is good enough:

try {
    //Exceptions may happen
} catch (Exception1 exception1) {
    //do stuff only in case of Exception1
} catch (Exception2 exception2) {
    some_method();
}
catch(Exception e) {
    some_method();
}

Where some_method would encapsulate the code related with "// do stuff in all exception cases except Exception1"

Consider encapsulating common code between catch clauses 2 & 3 on some method, for instance:

try {
   //code
} catch (Exception1 e1) {
   // specific code for exception 1
} catch (Exception2 e2) {
   // specific code for exception 2
   method();
} catch (Exception e) {
   method();
}

Catch two types of exception in one block with the "|" operator.. And maybe you can execute code that you have to execute in any case in the finally statement. That are all options you have, and i think creating a method and calling it isn't a option, when you're trying to make your code more readable, what I think you're trying to do

try {
     //code
} catch (Exception1 | Exception2 e2) {
    // specific code for exception 1 & 2
} catch (Exception e) {
    // handle other exceptions
} finally {
    // execute in any case 
}
Related