Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Exceptions versus flow control [closed]

Tags:

java

exception

The Effective Java Exceptions article describes a CheckingAccount which should processCheck(). Furthermore it states:

The natural way to represent the contingency responses in Java is to define two exceptions, say StopPaymentException and InsufficientFundsException

To me this sounds like exceptions used for flow control. Could you please explain why it is okay to use checked exceptions for flow control here? (Or whether this is no case of flow control.)

like image 979
Micha Wiedenmann Avatar asked Mar 13 '26 17:03

Micha Wiedenmann


1 Answers

Exceptions, particurarly of the checked variety, are perfect for flow control, but only for exceptional cases: if the exception is what predictably happens every time you run the code, because it is part of the "happy-day scenario", only then are you misusing them. The textbook example for that is using a while (true) loop to iterate over an array, counting on ArrayIndexOutOfBounds to break it.

Another concern taken care of by exceptions is "out-of-band signalling", where you have already occupied the method's return value for the "happy-day" data and you need another, distinguished channel to signal the reason why there is no data to return. In Haskell/Scala you'd use a Maybe monad for that; in Java you'd better stick with checked exceptions.

like image 198
Marko Topolnik Avatar answered Mar 16 '26 07:03

Marko Topolnik



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!