Question

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()
Was it helpful?

Solution

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()

OTHER TIPS

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top