2015-12-16 26 views
1

我有很多我的Django項目創建的自定義異常。像這樣捕獲所有自定義異常的Python

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 

回答

0

典型的方法是將您的所有異常建立共同的超類。

# 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 
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瞭解詳細信息)

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