Should I use "if" or "try" (as a matter of speed)?

Dark Cowherd darkcowherd at gmail.com
Mon Jul 11 11:48:40 EDT 2005


> 
> def joels_function(args):
>    error_result = 0
>    good_result = None
>    process(args)
>    if error_condition():
>        error_result = -1  # flag for an error
>    elif different_error_conditon():
>        error_result = -2
>    else:
>        more_processing()
>        if another_error_conditon():
>            error_result = -3
>        do_more_work()
>        good_result = "Success!"
>    if error_result != 0:
>        return (False, error_result)
>    else:
>        return (True, good_result)
> 
> 
> and then call it with:
> 
> status, msg = joels_function(args)
> if status == False:
>    print msg
>    # and fail...
> else:
>    print msg
>    # and now continue...
> 
> 
> This is how I would write it in Python:
> 
> def my_function(args):
>    process(args)
>    if error_condition():
>        raise SomeError("An error occurred")
>    elif different_error_conditon():
>        raise SomeError("A different error occurred")
>    more_processing()
>    if another_error_conditon():
>        raise SomeError("Another error occurred")
>    do_more_work()
>    return "Success!"
> 
> and call it with:
> 
> try:
>    result = my_function(args)
>    print "Success!!!"
> except SomeError, msg:
>    print msg
>    # and fail...
> # and now continue safely here...
> 
> 
> In the case of Python, calling a function that may raise an exception is

I tend to use exceptions, but I think Joel has a point.

Taking the example code that you have given above.

Let us assume that somebody else is using my_function and DOES NOT
write a try except block.

This code will run fine except, when the exception is thrown and it
will suddenly pop up in some other error handler which may not be
handling the situation correctly. You have to plan and create a series
of errorhandling classes to handle such situations.

However Joels_function forces the caller to write some kind of error
handler. If he doesnt write the program will not run.

After reading that I have been giving this option some thought. The
nice thing about Python is I can easily return tuples. In C++ you have
to jump through hoops because you cant return two values easily.

DarkCowherd



More information about the Python-list mailing list