2

I have the following code

    try {
        // code
    } catch (Exception1 e1) {
        if (condition) {
            //code
        } else {
            throw e1;
        }
    } catch (Exception2 e2) {
        if (condition) {
            //code
        } else {
            throw e2;
        }
    }

How can I use a private method to modularize the if-else block in both the catches.

More specifically, if i use a method how to pass the different exceptions to the method and throw them appropriately?

I followed this link, but did not understand how to pass and throw the right exceptions.

2
  • Can you format your code? Commented May 28, 2013 at 22:15
  • I have seen handling multiple exceptions in same catch. But I just want to use a method to replace the if-else block Commented May 28, 2013 at 22:19

4 Answers 4

7

If working with Java 7, you can use the new pipe syntax:

catch (Exception1|Exception2 e)
{
  if(condition) {
    //code
  } else {
    throw e;
  }
}
Sign up to request clarification or add additional context in comments.

2 Comments

That's awesome. I didn't know of that feature. Where can I get a concise list of all the new Java 7 language changes?
2

there are various ways, one simple way could be to define a method as:

private void method(Exception e){
if (condition) {
            //code
        } else {
            throw e1;
        }
}

then call it in your catch

try {
        // code
    } catch (Exception1 e1) {
        method(e1);
    } catch (Exception2 e2) {
        method(e2);
    }

Comments

2

This is as simple as putting the if/else in a method.

try {
    // code
} catch (Exception1 e1) {
    logic(e1);
} catch (Exception2 e2) {
    logic(e2);
}


private void logic(Exception e) throws Exception {
    if (condition) {
        //code
    } else {
        throw e;
    }
}

7 Comments

So I need not worry about downcasting the exceptions?
What if Exception2 extends Exception1 ? :)
@SairamSankaran No, Exception is the parent of all Exceptions. You don't need to cast.
@kocko what problem would that cause?
Well, if you handle two exceptions in a try/catch block, which are (lets say) father and son, you have to define the catch block in specific order - the first catch should be for the child, the next one should be for the father. Otherwise you won't be able to compile your code, as far as I remember. :)
|
0

The only thing you want to make sure to do in the answers people post is you need to put the Exception1 must not be superclass of Exception2 otherwise does not compile. Java 7 answer below is the best way to handle it and order matters as I explained

For list of changes in Java 7

http://www.oracle.com/technetwork/java/javase/jdk7-relnotes-418459.html

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.