Python - 我的 class 引发了 ValueError,但它没有被 except 处理
Python - My class raise ValueError, but it is not handled by except
我的示例代码:
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')
这只是一个例子!问题在于 ValueError 由第二个 class 引发,但不由第一个 class 的 except 子句处理。回溯下方:
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
如何正确处理?
谢谢,
试试这个
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')
为了实际处理该错误,您需要重写 tkinters 事件循环……不是很容易(或者一般来说是好的做法)
更好的方法是处理 go_click
函数自身的错误,例如
def go_click(self):
try:
self.submit_form()
except ValueError:
print "VALIDATION ERROR!!"
我的示例代码:
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')
这只是一个例子!问题在于 ValueError 由第二个 class 引发,但不由第一个 class 的 except 子句处理。回溯下方:
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
如何正确处理?
谢谢,
试试这个
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')
为了实际处理该错误,您需要重写 tkinters 事件循环……不是很容易(或者一般来说是好的做法)
更好的方法是处理 go_click
函数自身的错误,例如
def go_click(self):
try:
self.submit_form()
except ValueError:
print "VALIDATION ERROR!!"