[英]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.