繁体   English   中英

捕获所有自定义异常Python

[英]Catching all Custom Exceptions Python

我为Django项目创建了许多自定义例外。 像这样

errors.py

# General Exceptions

class VersionError(Exception):
    pass

class ParseError(Exception):
    pass

class ConfigError(Exception):
    pass

class InstallError(Exception):
    pass

但是我想从我的自定义异常而不是常规输出打印输出。 但不想将它们全部列出来,即

try:
   do something wrong
except <custom errors>, exc:
    print exc
except:
    print "Gen

您应该为自定义异常定义一个自定义标记基类:

# General Exceptions
class MyException(Exception):
    """Just a marker base class"""

class VersionError(MyException):
    pass

class ParseError(MyException):
    pass

class ConfigError(MyException):
    pass

class InstallError(MyException):
    pass

通过修改,您可以轻松地说出:

try:
   do something wrong
except MyException as exc:
    print exc
except:
    print "Some other generic exception was raised"

(顺便说一句,您应该使用推荐的except Exception as ex语法,而不是except Exception, ex ,有关详细信息,请参见此问题 。)

规范的方法是为所有异常创建通用的超类。

# General Exceptions
class MyAppError(Exception):
    pass

class VersionError(MyAppError):
    pass

class ParseError(MyAppError):
    pass

class ConfigError(MyAppError):
    pass

class InstallError(MyAppError):
    pass

通过这种继承,您可以简单地捕获MyAppError类型的所有异常。

try:
    do_something()
except MyAppError as e:
    print e

您应该为所有自定义异常创建一个通用基类,并加以捕获。

创建一个自定义基本异常,并从此基本执行中派生所有其他自定义异常:


class CustomBaseException(Exception):
    pass

# General Exceptions

class VersionError(CustomBaseException):
    pass

class ParseError(CustomBaseException):
    pass

class ConfigError(CustomBaseException):
    pass

class InstallError(CustomBaseException):
    pass

那你可以做


try:
   do something wrong
except CustomBaseExecption, exc:
    print exc
except:
    print "Gen

您可以对例外进行元组化:

my_exceptions = (VersionError,
                 ParseError,
                 ConfigError,
                 InstallError)

用法:

except my_exceptions as exception:
    print exception

例如:

>>> my_exceptions = (LookupError, ValueError, TypeError)
>>> try:
...     int('a')
... except my_exceptions as exception:
...     print type(exception)
...     print exception
<type 'exceptions.ValueError'>
invalid literal for int() with base 10: 'a'

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM