using exceptions for non-error purposes

exception, programming-languages

Solution

It depends on the language. Each language has it's own design and idioms. For most languages exceptions should be exceptional.

In languages like C++, Java and C# it is very bad form to use exceptions for anything else.

In Python, exceptions are used more frequently for things like the end of an iteration. There is much more of a model of try to do what you want and handle the exceptions later rather than validating input ("Easier to Ask Forgiveness than Permission"). For example if you want to open a file, in Java you might check if it exists first and then open it and check to see if you have a valid stream. In Python you would open it and use it. If that fails you handle the exception.

From the wikipedia article:

Python style calls for the use of exceptions whenever an error condition might arise. Rather than testing for access to a file or resource before actually using it, it is conventional in Python to just go ahead and try to use it, catching the exception if access is rejected.

Exceptions can also be used as a more general means of non-local transfer of control, even when an error is not at issue. For instance, the Mailman mailing list software, written in Python, uses exceptions to jump out of deeply-nested message-handling logic when a decision has been made to reject a message or hold it for moderator approval.

Problem

Is it a good practice to use exception for managing cases that are not errors ? Like in JavaScript and Python that manage the StopIteration case in generators (yield keyword).

Original source