DEV Community

Discussion on: What to Except When You're Excepting: Python error handling dos & don'ts

Collapse
 
swizzard profile image
sam

technically you don't, in this case, because of the return. but if you don't have a return you still need the else, and i'd argue it's clearer/more informative either way.

Collapse
 
khuongduybui profile image
Duy K. Bui • Edited

So I will end up having nested try? As in

try:
    foo
except FooException:
    print "foo"
else:
    try:
        bar
    except BarException:
        print "bar"
    else:
        try:
            # ... so on so forth

?

Thread Thread
 
swizzard profile image
sam

potentially! but like i said, it might be worth refactoring those cases into separate functions

Thread Thread
 
khuongduybui profile image
Duy K. Bui

So

def wrap_foo:
    try:
        foo
    catch FooException:
        print "foo"

def wrap_bar:
    # same as above

def main:
    wrap_foo
    wrap_bar

Am I getting there?

Thread Thread
 
swizzard profile image
sam

yeah, depending on what you're trying to do—if everything's decoupled and bar doesn't depend on the success of foo, then this approach is the way to go