2011-08-23 105 views
20

在Python中,捕获“所有”异常的最佳方法是什么?在Python中捕获所有异常

except: # do stuff with sys.exc_info()[1] 

except BaseException as exc: 

except Exception as exc: 

catch可能正在执行一个线程。

我的目的是记录可能由正常代码中抛出任何异常毫无遮拦任何特殊的Python例外,比如那些指示进程终止等

获取的句柄异常(如条款以上包含exc)也是可取的。

回答

20

如果您需要捕获所有异常和所有做同样的东西,我会建议你:

try: 
    #stuff 
except: 
    # do some stuff 

如果你不想掩盖“特殊”蟒蛇异常,使用异常基类

try: 
    #stuff 
except Exception: 
    # do some stuff 

相关管理一些例外,赶上他们明确:

try: 
    #stuff 
except FirstExceptionBaseClassYouWantToCatch as exc: 
    # do some stuff 
except SecondExceptionBaseClassYouWantToCatch as exc: 
    # do some other stuff based 
except (ThirdExceptionBaseClassYouWantToCatch, FourthExceptionBaseClassYouWantToCatch) as exc: 
    # do some other stuff based 

来自python文档的exception hierarchy应该是有用的阅读。

+1

感谢您的链接到的异常层次结构。 :) – EOL

0

为了避免掩盖基本的异常,您需要“重新引发”任何您不明确希望处理的异常,例如, (改编自8. Errors and Exceptions):

 
import sys

try: # do something that could throw an exception: except IOError as (errno, strerror): print "I/O error({0}): {1}".format(errno, strerror) except ValueError: print "Could not convert data to an integer." except: # maybe log the exception (e.g. in debug mode) # re-raise the exception: raise

+1

最后的'except:raise'不会做任何事情:它可以完全跳过;非IOError和非ValueError异常不会被捕获,并会被解释器自动引发。 – EOL

+1

@EOL你说得对。我编辑了我的答案,以指出为什么最后除外:可能有用。 – Peter

29
  • except Exception: VS except BaseException:

    捕捉ExceptionBaseException之间的区别在于,根据exception hierarchy异常等SystemExit,一个KeyboardInterrupt和GeneratorExit不会被捕获当使用except Exception时,因为它们直接从BaseException继承。

  • except: VS except BaseException:

    这两者之间的区别主要是在蟒2(AFAIK),它使用时的老式类作为要提出的一个例外,在这种情况下,仅只有表达少除了子句将能够捕捉到例外,例如。

    class NewStyleException(Exception): pass 
    
    try: 
        raise NewStyleException 
    except BaseException: 
        print "Caught" 
    
    class OldStyleException: pass 
    
    try: 
        raise OldStyleException 
    except BaseException: 
        print "BaseException caught when raising OldStyleException" 
    except: 
        print "Caught" 
    
+2

我按照正式推荐的方法(http://docs.python.org/tutorial/errors.html#user-defined-exceptions)从'Exception'继承'NewStyleException'。 – EOL