Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Avoid exceptions?

This particular example relates to Django in Python, but should apply to any language supporting exceptions:

try:
    object = ModelClass.objects.get(search=value)
except DoesNotExist:
    pass

if object:
    # do stuff

The Django model class provides a simple method get which allows me to search for one and only one object from the database, if it finds more or less it raises an exception. If can find zero or more with an alternative filter method, which returns a list:

objects = ModelClass.objects.filter(search=value)
if len(objects) == 1:
    object = objects[0]
    # do stuff

Am I overly averse to exceptions? To me the exception seems a little wasteful, at a guess, a quarter-to-a-half of the time will be 'exceptional'. I'd much prefer a function that returns None on failure. Would I be better to use Django's filter method and process the list myself?

like image 762
Mat Avatar asked Jan 03 '09 18:01

Mat


2 Answers

Believe it or not, this actually is an issue that is a bit different in each language. In Python, exceptions are regularly thrown for events that aren't exceptional by the language itself. Thus I think that the "you should only throw exceptions under exceptional circumstances" rule doesn't quite apply. I think the results you'll get on this forum will be slanted towards that point of view though, considering the high number of .Net programmers (see this question) for more info on that).

At a very minimum, I'd better not catch anyone who sticks to that rule ever using a generator or a for loop in Python (both of which involve throwing exceptions for non-exceptional circumstances).

like image 111
Jason Baker Avatar answered Oct 03 '22 18:10

Jason Baker


There's a big schism in programming languages around the use of exceptions.

  • The majority view is that exceptions should be exceptional. In most languages with exceptions, transfer of control by exception is considerably more expensive than by procedure return, for example.

  • There is a strong minority view that exceptions are just another control-flow construct, and they should be cheap. The Standard ML of New Jersey and Objective Caml compilers subscribe to that view. If you have cheap exceptions you can code some fancy backtracking algorithms in ways that are more difficult to code cleanly using other mechanisms.

I've seen this debate repeated many times for new language designs, and almost always, the winner decides that exceptions should be expensive and rare. When you care about performanced, you'd be wise to program with this in mind.

like image 29
Norman Ramsey Avatar answered Oct 03 '22 18:10

Norman Ramsey