简体   繁体   English

的Python-我的课引发ValueError,但不是由

[英]Python - My class raise ValueError, but it is not handled by except

My Sample Code: 我的示例代码:

from tkinter import *

class first:
    def __init__(self):
        self.top = Tk()
        ...
    def test(self):
        try:
            self.value = self.dict[key]
        except KeyError:
            try:
                second()
            except ValueError:
                print('Finally')

class second:
    def __init__(self):
        self.frame = Toplevel()
        ...
        self.button = ttk.Button(parent=self.frame, text='GO', command=self.go_click)
        ...

    def go_click(self):
        raise ValueError('Not Valid')

That´s just an example! 那只是一个例子! The problem is that the ValueError is raised by the second class, but it is not handled by the except clause of the first class. 问题是ValueError由第二个类引发,但没有由第一类的except子句处理。 Below the traceback: 下面的回溯:

Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Python34\lib\tkinter\__init__.py", line 1487, in __call__
    return self.func(*args)
File "........", line xxx, in goclick
    raise ValueError('Not Valid')
ValueError: Not Valid

How can I properly handle it? 我该如何正确处理?

Thanks, 谢谢,

try this 尝试这个

from tkinter import *

class first:
    def __init__(self):
        self.top = Tk()
        ...
    def test(self):
        try:
            self.value = self.dict[key]
        except KeyError:
            try:
                second()
            except ValueError:
                print('Finally')
            print "OK CALLED SECOND()!!!!" #######THIS PRINT MEANS YOUR DONE HERE

class second:
    def __init__(self):
        self.frame = Toplevel()
        ...
        self.button = ttk.Button(parent=self.frame, text='GO', command=self.go_click)
        ...

    def go_click(self):
        raise ValueError('Not Valid')

in order to actually handle that error you would need to override tkinters event loop ... not very easy(or good practice in general) 为了实际处理该错误,您需要重写tkinters事件循环...不太容易(或一般情况下的良好做法)

a better way to do it would be to handle the error in the go_click function its self something like 更好的方法是处理go_click函数中的错误,其自身类似于

  def go_click(self):
      try:
         self.submit_form()
      except ValueError:
         print "VALIDATION ERROR!!"

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

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