简体   繁体   中英

How do I handle user defined exceptions in Python?

If I have an Error module defined containing my application defined exceptions as something like:

class Error(Exception):
        pass

class NoSchemaVersion(Error):
        def __init__(self):
                self.code = 1
                self.msg  = "No schema version specified"
        pass


class NoMsgType(Error):
        def __init__(self):
                self.code = 2
                self.msg = "No message type specified"
        pass

How do I would I handle specific exceptions when they are raised. I tried something like:

import Error
errors = Error.Error()

try:
   <do some stuff>
except errors.NoMsgType:
   <stuff>

but I get the message:

AttributeError: 'Error' object has no attribute 'NoMsgType'

What am I doing wrong?

Error.Error() (stored in error ) constructs a new value of the Error class, but NoMsgType is a separate class that isn't actually part of Error , and so error.NoMsgType doesn't exist. To catch a NoMsgType , you should just write except Error.NoMsgType: .

I gues you need to do simething like this:

try:
    somecode
except Error.NoMsgType:
    morecode

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