1

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, i.e

try:
   do something wrong
except <custom errors>, exc:
    print exc
except:
    print "Gen
felix001
  • 15,341
  • 32
  • 94
  • 121

5 Answers5

3

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
Łukasz Rogalski
  • 22,092
  • 8
  • 59
  • 93
2

You could make a tuple of the exceptions:

my_exceptions = (VersionError,
                 ParseError,
                 ConfigError,
                 InstallError)

Usage:

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'
Peter Wood
  • 23,859
  • 5
  • 60
  • 99
1

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)

Community
  • 1
  • 1
plamut
  • 3,085
  • 10
  • 29
  • 40
0

You should make a common base class for all your custom exceptions, and catch that.

John Zwinck
  • 239,568
  • 38
  • 324
  • 436
0

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
Sebastian Stigler
  • 6,819
  • 2
  • 29
  • 31