Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/365.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 将类中引发的错误获取到main()_Python_Exception_Try Catch_User Defined_Raise - Fatal编程技术网

Python 将类中引发的错误获取到main()

Python 将类中引发的错误获取到main(),python,exception,try-catch,user-defined,raise,Python,Exception,Try Catch,User Defined,Raise,嗨,我现在正在做这样的节目 class MyError(Exception): def __init__(self, text = "Correct") self.text = text def __str__(self): return (self.kod) class Atom(self): . . . try: function() else: raise MyError("Incorrect

嗨,我现在正在做这样的节目

class MyError(Exception):
    def __init__(self, text = "Correct")
        self.text = text
    def __str__(self):
        return (self.kod)

class Atom(self):
.
.
.
    try:
        function()
    else:
        raise MyError("Incorrect use of function")


def main():
    try:
        a = Atom()
    except:
        # Here i want to print the error that was raised
我想我理解的是,在Atom()中创建的对象中引发了错误。 但是我想把它发送到我的主程序,并在那里打印错误MyError。 是否可以这样做?我应该如何编写它,以便打印正确的异常文本,因为我将有几个不同的错误消息


如果我使用except语句,我希望打印出“函数使用不正确”的消息。

您似乎非常接近:

class MyError(Exception):
    def __init__(self, text = "Correct")
        self.text = text
    def __str__(self):
        return (self.kod)

class Atom(self):
.
.
.
    try:
        function()
    except:  # try: ... else: raise ... seems a bit funky to me.
        raise MyError("Incorrect use of function")


def main():
    try:
        a = Atom()
    except Exception as err:  # Possibly `except MyError as err` to be more specific
        print err
诀窍在于,当捕捉到错误时,您希望使用
as
子句将异常实例绑定到一个名称。然后你可以打印它,查看它的属性,重新提升,或者用它做任何你选择的事情


请注意,此代码仍然不是“干净的”。一般来说,您希望尽可能地限制异常处理——只捕获期望看到并且知道如何处理的异常。否则,有时您可以屏蔽代码中难以发现的bug。因此:

try:
    do_something()
except:
    ...
不鼓励使用(它会捕获各种内容,如
键盘中断
系统退出
)。。。相反:

try:
    do_something()
except ExceptionIKnowHowToHandle:
    ...
建议。

首先,除了之外,不要做空白的
。这将捕获所有错误,包括
键盘中断
——因此您无法将ctrl-c移出程序。在这里,您应该只捕获
MyError

exception子句还允许您将实际异常分配给变量,然后可以打印该变量或对其执行任何其他操作。因此,您可以:

try:
    ...
except MyError as e:
    print e.text 

是的,您总是会得到最后一个错误——当然,您总是可以将原始错误添加为最终错误的属性,并在异常处理中加上它。