Home > OS >  Is there a way to combine an Else with a Catch in Java?
Is there a way to combine an Else with a Catch in Java?

Time:09-23

 if (condition) {
    try {

    } catch (Exception e) {
        throw new ...
    }

} else {
    throw new ....
}

I want to try and combine the two same exceptions being thrown. Is there any way of accomplishing this? Something like

if (condition) {

} else/catch {
    throw new ....
}

CodePudding user response:

Definitely not, which is good because there is no reason to do it. If you want to avoid code duplication consider creating a method that should be called in both catch and else blocks.

CodePudding user response:

You can write something like this:

try {
    if (condition) {
        // do something
    } else {
        throw new SomeCustomException();
    }
} catch (SomeCustomException | AnyOtherException e) {
    // do something else
}

....
static class SomeCustomException extends Exception { }

If it makes sense, you can throw only the AnyOtherException without creating the custom one.

  •  Tags:  
  • java
  • Related