2

I have somthing similar in my code below, where I have multiple except statements and all of them have to execute the someCleanUpCode() function. I was wondering if there is a shorter way to do it. Like a block that is only being executed when there was an exception. I can't use the finally block because that's also being executed when the try doesn't raise an error. And I only need to execute the someCleanUpCode() when there was an error. I first want to print the error and after that, run the someCleanUpCode()

try:
  dangerousCode()

except CalledProcessError:
  print "There was an error without a message"
  someCleanUpCode()
except Exception as e:
  print "There was an error: " +repr(e)
  someCleanUpCode()
3
  • 4
    I'm not aware of any other way to do this. I think the current code is fine - it makes it clear that someCleanUpCode is called in every error case. Commented Jul 30, 2014 at 14:26
  • Okay, I'll stick to that code ;) Commented Jul 30, 2014 at 14:27
  • Assuming the dangerous code is always a function, and you have lots of them, you might want to wrap it with an @foo wrapper that adds the try/except routine whenever the function is called. Commented Jul 30, 2014 at 15:09

2 Answers 2

1

Assuming CalledProcessorError subclasses Exception (which should be the case):

try:
   dangerous_code()
except Exception as e:
   print "There was an error %s" % ("without an error" if isinstance(e, CalledProcessError) else repr(e))
   some_cleanup_code()

or if you have more to do:

try:
   dangerous_code()
except Exception as e:
       try:
   dangerous_code()
except Exception as e:
   if isinstance(e, CalledProcessError):
       print "There was an error without a message"
   else:
       print "There was an error: " +repr(e)
   some_cleanup_code()
Sign up to request clarification or add additional context in comments.

2 Comments

I see, you can do it like this. But this can become very messy when I've got more than two excepts :). But thanks for this code.
Yes if you have half a dozen except clauses each with it's own specific stuff, your current structure is possibly cleaner... but it's not DRY.
1

are you looking for something like this?

try:
    1/0
except (ValueError, ZeroDivisionError) as e:
    print e
    # add some cleanup code here


>>>integer division or modulo by zero

This catches multiple exceptions

1 Comment

But the problem is that only a part of the code is shared. Not the entire code is the same.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.