Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Forcing code flow to go to except block

Tags:

python

I have:

try:
   ...
except Exception, e:
   print "Problem. %s" % str(e)

However, somewhere in try, i will need it to behave as if it encountered an Exception. Is it un-pythonic to do:

try:
   ...
   raise Exception, 'Type 1 error'
   ...

except Exception, e:
   print "Problem. Type 2 error %s" % str(e)
like image 452
user1008636 Avatar asked Sep 12 '12 18:09

user1008636


2 Answers

I think this is a bad design. If you need to take some action if (and only if) an exception wasn't raised, that is what the else clause is there for. If you need to take some action unconditionally, that's what finally is for. here's a demonstration:

def myraise(arg):
    try:
        if arg:
            raise ValueError('arg is True')
    except ValueError as e:
        print(e)
    else:
        print('arg is False')
    finally:
        print("see this no matter what")

myraise(1)
myraise(0)

You need to factor the unconditional code into finally and put the other stuff in except/else as appropriate.

like image 163
mgilson Avatar answered Oct 18 '22 07:10

mgilson


I think what you are doing is "unPythonic". Trys should really only cover the small part (ideally one line) of the code which you expect might sometimes fail in a certain way. You should be able to use try/except/else/finally to get the required behaviour:

try:
    #line which might fail
except ExceptionType: # the exception type which you are worried about
    #what to do if it raises the exception
else:
    #this gets done if try is successful
finally:
    #this gets done last in both cases (try successful or not)
like image 29
Andy Hayden Avatar answered Oct 18 '22 06:10

Andy Hayden