Chinmay
Chinmay

Reputation: 751

Are exception flow control better in certain scenarios?

There are many articles explaining why exception flow control should be avoided and is considered an anti-pattern. However, does using exception flow control makes sense in following example?

Eg: I have an enum type with many values and need to check if it contains a given string.

The solution using Enum.valueof shall throw an IllegalArgumentException and can be used to return false. Even Apache commons lang3 lib uses same. We reuse one time lazy initialized enumConstantDirectory map on all subsequent calls.

return EnumUtils.isValidEnum(MyEnum.class, myValue);

Other solution would be to iterate.

return Stream.of(MyEnum.values()).anyMatch(e -> e.name().equals(value));

Upvotes: 3

Views: 79

Answers (1)

GhostCat
GhostCat

Reputation: 140525

Programming is always about balancing between "informal standards" and deviating from rules where it makes sense.

Yes, Java is one of those languages where you "look before you leap" (you check conditions); not like Python where you "ask for forgiveness" (not for permission).

In other words: most of the time, a Java programmer would find it surprising to look at code that uses exceptions for control flows. But: that doesn't mean that one never should work this way.

My personal two cent here: I think you should rely on exceptions when that case indicates a real exceptional condition in your program. Meaning: when those strings you are checking are supposed to represent enum constants ... than an exception might be fine. But when there is a certain chance (and maybe even "valid" reasons) at runtime that a string is invalid, then I would rather use a method that goes boolean isValid() and not throw an exception.

Upvotes: 7

Related Questions