简体   繁体   中英

Catching all Custom Exceptions Python

I have a number of custom exceptions created for my Django project. like so

errors.py

# General Exceptions

class VersionError(Exception):
    pass

class ParseError(Exception):
    pass

class ConfigError(Exception):
    pass

class InstallError(Exception):
    pass

However I want to print the output from my custom exceptions but not the general. But do not want to list them all out, ie

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

You should define a custom marker base class for your custom exceptions:

# 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

With that modification, you can then easily say:

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

(BTW, you should use the recommended except Exception as ex syntax instead of the except Exception, ex , see this question for details)

Canonical way would be to create common superclass for all your exceptions.

# General Exceptions
class MyAppError(Exception):
    pass

class VersionError(MyAppError):
    pass

class ParseError(MyAppError):
    pass

class ConfigError(MyAppError):
    pass

class InstallError(MyAppError):
    pass

With this inheritance three you may simply catch all exceptions of type MyAppError .

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

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

Create a custom base exception and derive all the other custom exceptions form this base execption:


class CustomBaseException(Exception):
    pass

# General Exceptions

class VersionError(CustomBaseException):
    pass

class ParseError(CustomBaseException):
    pass

class ConfigError(CustomBaseException):
    pass

class InstallError(CustomBaseException):
    pass

Then you can do


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

You could make a tuple of the exceptions:

my_exceptions = (VersionError,
                 ParseError,
                 ConfigError,
                 InstallError)

Usage:

except my_exceptions as exception:
    print exception

eg:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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