捕获所有自定义异常Python

时间:2015-12-16 08:42:12

标签: 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

5 个答案:

答案 0 :(得分:1)

您应该为自定义例外定义自定义标记基类:

# 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,有关详情,请参阅this question

答案 1 :(得分:1)

规范的方法是为所有例外创建公共超类。

# 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

答案 2 :(得分:0)

您应该为所有自定义异常创建一个公共基类,并抓住它。

答案 3 :(得分:0)

创建自定义基本异常并从此基本execption派生所有其他自定义异常:


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

答案 4 :(得分:0)

你可以做出例外的元组:

my_exceptions = (VersionError,
                 ParseError,
                 ConfigError,
                 InstallError)

用法:

except my_exceptions as exception:
    print exception

e.g:

>>> 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'