2

I came to python from Node.js and I'm accustomed to such error handling:

doSmth(function(err, data) {
    if (err) {
        log(err);
    } else {
        fooSmth(data, function(err, res) {
            if (err) ...
        })
    }
})

Is it acceptable in Python to handle errors like

def do_smth(arg):
    try:
        data = int(arg)
        return None, data
    except Exception as e:
        logger(e)
        return e, None


err, data = do_smth("1715")
if not err:
    print data

So that the function always return a tuple with exception and data values:

(None, data) or (Exception, None)

2
  • 1
    Python has a good handling of exceptions, there is no reason to avoid using it just because you are used to another way (which is heavily based on asynchronous programming) from another language. Commented Nov 24, 2014 at 10:37
  • 1
    If you do it that way you'll end up duplicating the exception handling code everywhere, that's a lot of extra code. Also, when you have exception handling anywhere that isn't the outermost level of your program you should make it as specific as possible and only catch those errors you expect and know how to handle. Don't catch Exception when ValueError will do. Commented Nov 24, 2014 at 10:41

2 Answers 2

6

The Pythonic way would be to either move the try outside do_smth:

def do_smth(arg):
    return int(arg)

try:
    data = do_smth("1715")
except ValueError: # test for a specific error wherever possible
    logger.exception()
else:
    print data

or to return None in a failing case:

def do_smth(arg):
    try:
        return int(arg)
    except ValueError:
        logger.exception()

data = do_smth("1715")
if data is not None: # test singletons with is
    print data

Note that Python generally has a preference for "easier to ask for forgiveness than permission"-style coding.

Sign up to request clarification or add additional context in comments.

2 Comments

I like the EAFP mention. :)
@jonrsharpe I didn't think about that in the case of an exception function returns 'None'. Thanks a lot
1

Although there is no error in your code, you usually don't pass exceptions as arguments into other scopes unless the exception instance will be actually used as data. Exceptions in Python are lightweight and they bubble up to render a full traceback, so you must just let them live and happen.

If you expect some kind of exception happen when you call do_smth, just write code to handle it, like this:

# Definition
def do_smth(arg):
    return int(arg)


# Usage elsewhere
try:
    data = do_smth(['invalid', 'number'])
except TypeError:
    print('Incompatible type!')
except ValueError:
    print('Not a number.')
else:
    print('Conversion successful.')

Pro tip: avoid catching just Exception. Always expect specific types of errors, get used to write and raise your own exceptions as well. It helps a lot. Read more about it. ;)

PS: I also come from JavaScript as primary language; I'm sure you'll love Python too. :)

2 Comments

JavaScript -> CoffeeScript -> Python || JavaScript -> Python ?
I was JavaScript from the rootz, before CoffesScript existed. I like it though, have tried in my latest projects. I'm more [hapilly] CoffeeScript || Python nowadays. :)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.