简体   繁体   English

如何在Python中处理用户定义的异常?

[英]How do I handle user defined exceptions in Python?

If I have an Error module defined containing my application defined exceptions as something like: 如果我定义了一个Error模块,其中包含我的应用程序定义的异常,例如:

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. Error.Error() (存储在error )构造Error类的新值,但是NoMsgType是一个单独的类,实际上不是Error一部分,因此error.NoMsgType不存在。 To catch a NoMsgType , you should just write except Error.NoMsgType: . 要捕获NoMsgType ,您只需要编写except Error.NoMsgType:

I gues you need to do simething like this: 我猜你需要做这样的事情:

try:
    somecode
except Error.NoMsgType:
    morecode

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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