Skip to main content
 首页 » 编程设计

Python:使用几乎相同的代码 try catch 多个异常

2024年10月25日8cloudgamer

我在下面的代码中有一些类似的东西,其中我有多个 except 语句,并且所有这些语句都必须执行 someCleanUpCode() 函数。我想知道是否有更短的方法来做到这一点。就像一个只有在出现异常时才会执行的 block 。我不能使用 finally block ,因为当 try 没有引发错误时它也会被执行。而我只需要在出现错误时执行 someCleanUpCode() 。我首先要打印错误,然后运行 ​​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() 

请您参考如下方法:

假设 CalledProcessorError 是 Exception 的子类(应该是这样):

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

或者如果您还有其他事情要做:

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