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.