14

I want to handle exceptions of two different types differently, and after that to make some same actions for both exception types. How to do that in Java?

The following code shows what I want to do, but it is not correct, as one exception can not be caught twice.

What is the right syntax for this?

try {
    // do something...
} 
catch (ExceptionA e) {
    // actions for ExceptionA
}
catch (ExceptionB e) {
    // actions for ExceptionB
}
catch (ExceptionA | ExceptionB e) {
    // actions for ExceptionA & ExceptionB
}
8
  • Create your own custom exception class.
    – 2787184
    Commented Aug 7, 2015 at 13:21
  • 1
    You can put the code in functions and call the functions in the catch block.
    – Jens
    Commented Aug 7, 2015 at 13:23
  • @Jens That's not a solution, that's simply offloading the issue somewhere else...
    – insidesin
    Commented Aug 7, 2015 at 13:24
  • @Rob I use Java 7. This is not duplicate. As you can see, I actually use the construct from that topic. Commented Aug 7, 2015 at 13:25
  • @insidesin No if OP write three function handleExceptionA,handleExceptionB and handleExceptionAandB so he cann coll the methods in catch block.
    – Jens
    Commented Aug 7, 2015 at 13:27

5 Answers 5

10

Use the catch (ExceptionA | ExceptionB e) construct. Within the catch block, first do an instanceof check for e and handle the exception types separately. After this, have the common handling for both types. This way you can do everything in one catch block:

try {
    // do something...
} catch (ExceptionA | ExceptionB e) {
    if (e instanceof ExceptionA) {
        // handling for ExceptionA
    } else {
        // handling for ExceptionB
    }
    // common handling for both exception types
}
2
  • 1
    Or you could nest two try catch blocks one that handles the two seperately the other that handle the common piece. the order would depend if the thing you want to do in one or the other depends on each other :).
    – Rob
    Commented Aug 7, 2015 at 13:25
  • @Mick Mnemonic I used your solution, as it is the most easily readable and clear. Commented Aug 10, 2015 at 7:25
3

Use a method for the common code.

try {
    // do something...
} 
catch (ExceptionA e) {
    // actions for ExceptionA
    doCommon(parameters);
}
catch (ExceptionB e) {
    // actions for ExceptionA
    doCommon(parameters);
}

.....

void doCommon( parameters ) {
  // actions for ExceptionA & ExceptionB
}

That will work for most things.
Though there are some exceptions like return. For that you can have doCommon return wether the caller has to return or not and use it as :

catch (ExceptionA e) {
    // actions for ExceptionA
    if ( doCommon(parameters) )
      return;
}
catch (ExceptionB e) {
    // actions for ExceptionA
    if ( doCommon(parameters) )
      return;
}

A "native Java" solution does not exist. JLS specifies (emphasis mine) :

14.20.1. Execution of try-catch

A try statement without a finally block is executed by first executing the try block. Then there is a choice:

If execution of the try block completes normally, then no further action is taken and the try statement completes normally.

If execution of the try block completes abruptly because of a throw of a value V, then there is a choice:

If the run-time type of V is assignment compatible with (§5.2) a catchable exception class of any catch clause of the try statement, then the first (leftmost) such catch clause is selected. The value V is assigned to the parameter of the selected catch clause, and the Block of that catch clause is executed, and then there is a choice:

If that block completes normally, then the try statement completes normally.

If that block completes abruptly for any reason, then the try statement completes abruptly for the same reason.

If the run-time type of V is not assignment compatible with a catchable exception class of any catch clause of the try statement, then the try statement completes abruptly because of a throw of the value V.

So only the first catch block which applies is executed. There is no way to execute two catch blocks for the same try statement.

2
  • Method extraction is, of course, a solution. But I'm interested if there is a native try/catch construct for it. Commented Aug 7, 2015 at 13:38
  • 1
    No, there is no such construct. I've updated my answer with the relevant part of the JLS. Commented Aug 7, 2015 at 13:45
3

Would a solution of this type work for you:

try {
// do something...
} catch (ExceptionA | ExceptionB e) {
    // common code to be called for both...
    // ....
    handleException(e)
}

//.... 
void handleException(ExceptionA e) {
   // code for A
}
//....
void handleException(ExceptionB e) {
   // code for B
}

In this way first you do the common actions for the two issues, afterwards you have the common code for each of the exceptions in the appropriate method. In this way you don't need to use instanceof or ifs.

Another way of doing it only by using java constructs is by putting in the finally as well:

boolean fail = false;

try {
  // your code
} catch (ExceptionA a) {
   // exceptionA specific handling
   fail = true;
} catch (ExceptionB b) {
   // exceptionB specific handling
   fail = true;
} finally {
    if (fail) {
       // common handling
    }
}
1
  • 1
    Have you tried the top solution yourself? This does not work for me, because the compiler cannot resolve the method handleException(ExceptionA | ExceptionB). You would have to change the signature to handleException(Exception e) which defeats the purpose... Commented Feb 7, 2018 at 9:28
1

If you are seeking (ExceptionA | ExceptionB) you will be able to catch either and handle identically, only one will be required to fail. This is essentially just new (1.7) shorthand for multiple Exception conditions.

There is no such thing as catch(ExceptionA && ExceptionB).

For example:

readFile {
    try {
        open the file;
        determine its size;
        determine its content;
    } catch (fileOpenFailed) {
       doSomething;
    } catch (sizeDeterminationFailed) {
        doSomething;
    } catch (contentDeterminationFailed) {
        doSomething;
    }
}

If you wanted to catch contentDeterminationFailed and sizeDeterminationFailed as the single exception then you would want to create your own custom exception type which can be handled uniquely.

0

You can rethrow the exception and handle it again:

try {
    try {
        // do something
    } catch( ExceptionA e) {
        // actions for ExceptionA
        throw e;
    } catch( ExceptionB e) {
        // actions for ExceptionB
        throw e;
    } 
} catch( ExceptionA | ExceptionB e) {
    // Actions for exceptions A or B
}

Maybe, for sake of clarity, you could refactor into methods. I'm assuming the exceptions are checked exceptions.

private void doSomethingHelper() throws ExceptionA, ExceptionB {
    try {
        // do something
     } catch( ExceptionA e) {
         // actions for ExceptionA
         throw e;
     } catch( ExceptionB e) {
         // actions for ExceptionB
         throw e;
     } 
}

public void doSomething() {
    try {
        doSomethingHelper();
    } catch( ExceptionA | ExceptionB e ) {
        // Actions for exceptions A or B
    }
}
5
  • That does nothing but complicate the situation... The last catch solves the issue by itself.
    – insidesin
    Commented Aug 7, 2015 at 13:36
  • 1
    @insidesin I don't agree, it is a nested try block. The innter catch can handle the exception A or B individually, while the outer one can do general handling for either after the inner one exectues.
    – yas
    Commented Aug 7, 2015 at 13:37
  • So you're handling it twice for what reason? If you really need to, do an instanceof..
    – insidesin
    Commented Aug 7, 2015 at 13:41
  • 1
    @insidesin it is more flexible and easier to maintain than using instanceof
    – yas
    Commented Aug 7, 2015 at 13:47
  • Methods, no. Double clause? maybe. instanceof provides one level of conditionals, this will always be > 2.
    – insidesin
    Commented Aug 7, 2015 at 13:53

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.