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.

Daniel Kaplan
  • 62,768
  • 50
  • 234
  • 356
Sairam Sankaran
  • 309
  • 9
  • 18

4 Answers4

7

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

catch (Exception1|Exception2 e)
{
  if(condition) {
    //code
  } else {
    throw e;
  }
}
DannyMo
  • 11,344
  • 4
  • 31
  • 37
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);
    }
Ankit
  • 6,554
  • 6
  • 49
  • 71
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;
    }
}
Daniel Kaplan
  • 62,768
  • 50
  • 234
  • 356
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

Hamed Moghaddam
  • 564
  • 3
  • 8