【问题标题】:Exception not being handled by the try-except block in PythonPython中的try-except块未处理异常
【发布时间】:2019-05-20 09:56:07
【问题描述】:

我编写了一个简单的 python 代码,用于输入用户的任意数字。如果输入其他任何内容,则会根据代码引发异常。我将输入的值类型转换为 int 只是为了检查它是否是整数。理想情况下,除了当我输入任何字母表时,应该引发异常并打印我给出的文本。但我仍然可以看到它没有被抓住。

但是,当我专门在 typecast 语句周围再添加一个 try-except 块时,它就可以工作了。


from tkinter import *

window = Tk()
window.geometry('400x400')

class hangman:
    def __init__(self):
        self.entry = ''

    def clicked(self, label2):
        label2.place(x=100, y=200)

        while True:
            try:
                def get_value(event):
                    self.entry = e1.get()
                    self.entry = int(self.entry)
                    print(self.entry)

                Label(window, text="Enter any number :").place(x=10, y=220)

                e1 = Entry(window)
                e1.place(x=10, y=240)
                e1.bind('<Return>', get_value)  #To get the value entered in the entry when Return is pressed.
                print("Past bind1")
                print(self.entry)
                print("Past bind2")
                break

            except ValueError as e :
                print("\n\tPlease Enter only Numbers!!")


obj1    = hangman()
label2  = Label(window, text="Start")
bt      = Button(window, text="Play", command=lambda: obj1.clicked(label2))

bt.place(x=150, y=125)

window.mainloop()

我希望捕获异常并打印我的消息而不是标准异常错误。

【问题讨论】:

  • 当我输入 asdf 时出现异常。 ValueError: int() 以 10 为底的无效文字:'asdf'
  • @ShubhamSharma :是的,我希望这个错误由​​我写的 except 块处理。
  • 是的,它正在我的电脑上运行并给我执行消息。
  • 您需要查看终端以获取异常消息。不在 UI 屏幕上。
  • 是的,在终端屏幕上获取异常。虽然我期待消息:“请仅输入数字!”

标签: python-3.x exception tkinter


【解决方案1】:

如果你把 try/except 块放在get_value 函数中,异常会被正确捕获:

from tkinter import *
window = Tk()
window.geometry('400x400')


class hangman:
    def __init__(self):
        self.entry = ''

    def clicked(self, label2):
        label2.place(x=100, y=200)

        while True:
            def get_value(event):
                try:
                    self.entry = e1.get()
                    self.entry = int(self.entry)
                    print(self.entry)
                except ValueError as e:
                    print("\n\tPlease Enter only Numbers!!")

            Label(window, text="Enter any number :").place(x=10, y=220)

            e1 = Entry(window)
            e1.place(x=10, y=240)
            e1.bind('<Return>', get_value)  # To get the value entered in the entry when Return is pressed.
            print("Past bind1")
            print(self.entry)
            print("Past bind2")
            break


obj1 = hangman()
label2 = Label(window, text="Start")
bt = Button(window, text="Play", command=lambda: obj1.clicked(label2))

bt.place(x=150, y=125)

window.mainloop()

【讨论】:

  • 这不是重点。关键是为什么这个尝试 except 不起作用。
  • 我已经想通了,但是如果效果不佳,我正在尝试另一种直接从方法中引发异常的方法
  • @Stanisław Wilczyński:是的,它工作得非常好。但是有什么原因导致前一个不能正常工作?因为在该方法定义之外可能还有其他语句,这将需要异常处理。
  • 我认为您正在寻找的解决方案是使用report_callback_exception - 查看this question
猜你喜欢
  • 2015-09-10
  • 1970-01-01
  • 1970-01-01
  • 2017-04-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-31
  • 1970-01-01
相关资源
最近更新 更多