Pedru
Pedru

Reputation: 1450

Python, simple error handling pattern

I'm quite new to Python. I was wondering how to achieve simple error handling without using exceptions, what sometimes (I think) is overkill. I came up with a pattern, but I'm not sure if it is the pythonic way:

def someFunct(someArgs):
    # do stuff...
    if error:
        return False, 'error message'
    return True,None

and the caller would do something like this

success,errMsg = someFunct(myAwesomeArgs)
if success:
    # yey!
else:
    # handle error

Upvotes: 2

Views: 2012

Answers (4)

user850498
user850498

Reputation: 727

def someFunct(someArgs):
    try:
    # do stuff...
    return True,None
    except:
        return False, 'error message'

if you know what error might be raised you can use:

    except errorType1:
        return False, 'very bad'
    except errorType2:
        return False, 'very very bad'
    except errorType3:
        return False, 'the computer is dead. get a new one'

and so on.

Upvotes: 0

mandel
mandel

Reputation: 2947

Using exceptions in python is not an overkill what so ever. Exceptions in python are used in several places to control the flow of your application, for example, lets imaging you have the following method using your pattern:

def some_function(*args):
    """Do stuff using a loop."""

    for i in [1, 2, 3, 4]:
        print i

    return True, None

In there, there is already an exception which is the StopIteration exception, that is, even when you tried to avoid the use of exception it is internally used. So my answer is, use exceptions, this is not Java, C# etc.. where exceptions are utterly expensive compared with the rest of the code and you are just making you code unpythonic.

Upvotes: 3

Senthil Kumaran
Senthil Kumaran

Reputation: 56841

You would do just like you did. :) But yeah, handing errors via exception is not exceptional, it is quite common in python, so idiomatically you would want to use exception. But here is your code (bit changed)

def somefunc(*args):

    # do stuff, return -1 on eror
    error_value = do_suff()
    if error_value == -1:
          return True, "error message"
    else:
          return False, None

success, err = somefunc(1,2)

if success:
   # yay!
else:
   # handle error

Upvotes: 0

Marcin
Marcin

Reputation: 49826

Just use exceptions - it's the standard python way: http://docs.python.org/tutorial/errors.html

Upvotes: 3

Related Questions