views:

38

answers:

3

Occasionally in my code I will intentionally use a thrown exception as an event trigger. For instance, I will loop UNTIL an exception is thrown and then break; in the catch clause. Is this bad practice? Would it be more efficient (or cleaner) to query some attribute of what I am looping to predetermine the indices (i.e. predetermine when to stop looping)? Of course I only do this when I am sure that an exception will in fact be thrown to avoid an infinite loop. Thanks!

A: 

Yes, this is bad practice. Exceptions should be used for things that are exceptional - e.g. conditions that are true errors that should not occur in the normal course of operation.

One important reason is that exceptions are expensive in terms of CPU time.

It will be much more efficent, and likely much easier to debug and verify if you use a flag or other signal to terminate your loop.

Foredecker
A: 

It's bad practice to throw an exception as part of normal program control flow. Exceptions should be reserved for exceptional events such as error handling.

It's also not so great to loop continually waiting for some event to happen. Check out the Observer design pattern for the right way to code this type of thing.

Asaph
Would the downvoter care to comment?
Asaph
+2  A: 

This isn't really a language-agnostic issue!

Some languages, such as Python, have reasonably light-weight exceptions, and they make the use of exceptions for control flow a pretty unobjectionable approach -- for example, every for statement in Python (unless prematurely terminated by a break) is always terminated when an exception occurs (a StopIteration exception from the iterator used in the for). Any user of Python cannot therefore object to a loop systematically terminated by exceptions... unless they never, ever use for loops (pretty unlikely;-).

Other languages consider exceptions to be a really exceptional occurrence, and in those languages you shouldn't use them for ordinary flow-control tasks; apparently all the answers currently given to your question take this for granted in a "language agnostic" way, ignoring the existence or the actual nature or languages such as Python.

Those of us who know both kinds of languages reasonably well learn to "swim with the flow": I'd have no problems using exceptions for flow control in Python, but I'd definitely avoid doing so in C++, for example!

Alex Martelli