views:

264

answers:

10

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).

+10  A: 

I would say No, spontaneously. Exceptions should be used for exceptional states, not for regular program flow.

Fredrik Mörk
Sometimes it is not so easy to distinguish between exceptional and regular cases.
Soubok
Care to give an example?
tomfanning
@Suobok I'm at a loss as to when the distinction would be difficult. Can you give an example of a case were the lines are blurred between regular case and exceptional case?
Colin Mackay
Sorry - I don't see anything in that example that would justify using an exception. Perhaps it is fine in Python, I wouldn't do it in C#.
Colin Mackay
Imagine you are looking for something in a tree and you use recursion. When you find what you are looking for, you just throw the item.
Soubok
Ugh! That's not exceptional. That's expected! Just return the item. Since it is recursive the calling method is the same as has been returned and it can easily continue to return the item until it has hit the top of the stack. Normal expected behaviour. It is not in any way shape or form exceptional to find something you were looking for. And returns are cheaper than throwing exceptions in many languages too.
Colin Mackay
Finding the good node among 1000000 nodes is nearly exceptional :)
Soubok
@Soubok: Exceptional for a human, but not a computer ;o)
Fredrik Mörk
@Soubok poor example. As Colin says, just return the item. Try measuring the performance of throwing and catching an exception. You'll find there's a hell of a hit...
tomfanning
A method has a purpose. If it can acomplish its purpose, great, return the value. If it can't throw an exception. How to know the purpose? Well, generally the programmer knows it very well (or SHOULD KNOW! if he/she wants to have a clear design). If it's already programmed... read the method name! :D
helios
It's a question also for good error management: methods that can't acomplish their goal must fail (throw an exception) so somebody superior can handle the exception: show a nice message 99.9% of the time. But... don't use exception for other purposes except you have a very (exceptional :) good reason.
helios
+10  A: 

Not usually, no. ASP.NET uses this for Response.Redirect - actually aborting the thread, then catching the exception and resetting it. It's very nasty, but it does let you basically "quit" the request without every level of the stack being aware that it needs to return immediately.

Try to avoid wherever possible. If you think you absolutely have to do it, consult two colleagues, present the design and ask if they can do it more cleanly somehow. If none of you can think of a better way round it, do it with extensive documentation.

Jon Skeet
Perhaps sometimes throwing an exception is clearer that a lot of nested 'return' statements ?
Soubok
@Soubok: Hmm... Very rarely. It would be a pretty "exceptional" situation, to be honest. I'd really try to avoid it in all normal situations.
Jon Skeet
Downvoter: Care to give a reason?
Jon Skeet
+3  A: 

As the name says exceptions should only be used in Exceptional cases. I would not use it for managing non error cases.

chikak
+2  A: 

No.

Exceptions should only be used for exceptional situations (as the name says). That means: errors.

  • “Uh, I can’t find this file.” - Exception!
  • “Uh, I can’t divide by 0.” - Exception!
  • “Uh, I can’t get no memory.” - Exception!
  • “The result is 2.5." - No exception!
Bombe
Sometimes, not being able to find a file isn't exceptional either. Especially if the file is user input. Now, if it's a file you NEED and if it's not in one place, it's a sign of problems, that's an Exception.
Thomas Owens
Deep in the bowels of your application it still is an exception, of course you have to beautify it before showing it to the user.
Bombe
+1  A: 

No.

Generally the system is designed to make non-exception cases fast, while accepting exceptional cases take a performance hit. Thus a lot of exceptions being thrown/caught will be slower than conventional constructs.

It also makes analysis and understanding the code harder, and most code spends most of its time in maintenance.

Richard
Just note that Python and JavaScript are using the StopIteration exception to manage the end of a generator because it is cheaper than calling a method at each iteration to know if it is the end.
Soubok
"Generally" can have exceptions (pun intended).
Richard
... and that platform implementers can work to different rules (after all they can modify the platform's dynamics to suit the solution).
Richard
+2  A: 

It's a very questionable practice. If you feel it's the best thing for your situation regardless, make sure to document and comment it thoroughly to keep your WTF/m down.

chaos
+6  A: 

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.

Matt Price
+1  A: 

I believe that sometimes exceptions are useful for building DSLs. I know, it sounds weird, but as many languages don't have the features Ruby has (the return keyword is optional because the result of the last evaluated expression is returned), we use what we can.

For example, I recently tried to build a little JavaScript testing framework, and I wanted a way for the framework users to be able to say:

skip();
pending("pending message");
fail("failure message");

instead of:

return skip();
return pending("pending message");
return fail("failure message");

These functions would be library functions which throw exceptions like a SkipTest exception for example. The only recommended place to use them is inside test methods. These test methods are always executed in a try/catch block where every type of exception is treated and, depending on the exception the framework takes the appropriate step.

This is an example where I've used Exceptions for control flow.

Here's a small example:

$.it("should offer means to explicitly mark a spec as failed", function() {
    $.fail("this spec must fail");
});
Ionuț G. Stan
A: 

I've seen Python code that uses exceptions to test if input is of the correct type

try:
   n = int(n1)
except (ValueError, TypeError):
   # return an eror

Is this poor form, or does it qualify as an "exceptional case"?

Justin
You should start a new question for this (if it wasn't asked before), not post it as an answer to an old question. The "Ask Question" button is in the top right.
sth
it's already there: http://stackoverflow.com/questions/1152541/is-it-better-to-use-exception-or-return-code-in-python
Bartosz Radaczyński
+1  A: 

In a sudoku solver I wrote, an exception is thrown in case the puzzle is solved.

The main search function, a private method, descends into the search tree by making recursive calls to itself. The normal case is failure to solve the puzzle, which results in just a normal return to the caller; the exceptional case is success in solving the puzzle, in which case we "throw(solution)" all the way out to a catch clause in a public method.

Something like this is a known idiom in Scheme, using call/cc. I was imitating that in my C++ program.

I'd be delighted to hear anybody's pro or con opinions on this approach.

George Kangas