我已经完成了一个简单的应用程序来计算BMI,但是,我需要在另一个文件中创建一些异常处理,比如例外.py你知道吗
这些异常包括:空值异常、整数值异常和电子邮件格式异常。你知道吗
有人能告诉我如何在另一个文件中进行这些异常处理吗?你知道吗
from tkinter import *
from tkinter import ttk
from tkinter import messagebox
from exceptions import exceptions
import math , decimal
class BMI_Caclulator:
def __init__(self,master):
master.title = ('BMI Calculator')
[distracting UI construction code omitted]
def calculate(self):
print('Name: {}'.format(self.entry_name.get()))
print('Email: {}'.format(self.entry_email.get()))
print('Age: {}'.format(self.age.get()))
print('Gender: {}'.format(self.gender.get()))
print('Weight: {}'.format(self.entry_weight.get()))
print('Height: {}'.format(self.entry_ft.get())+ ' feets ' + format(self.entry_in.get())+ ' inchs' )
print('BMI:' + str(self.calculate_BMI()))
print('Comments: {}'.format(self.text_comments.get(1.0, 'end')))
self.clear()
messagebox.showinfo(title = 'BMI Calculator', message = 'Your information was successfully Submitted!')
def clear(self):
self.entry_name.delete(0, 'end')
self.entry_email.delete(0, 'end')
self.text_comments.delete(1.0, 'end')
def calculate_BMI(self):
self.inchs = int(self.entry_ft.get())* 12 + int(self.entry_in.get())
self.BMI = int(self.entry_weight.get())* 703 /math.pow(self.inchs,2)
return self.BMI
Pythonista的观点是,您不需要创建新的异常,因为在大多数情况下,它们都是为您创建的。你知道吗
例如,如果您尝试从空条目创建int,
int('')
将自身引发ValueError
。问题是应该在哪里处理异常。 函数calculate
是异常可能发生的地方,因此在这里可以捕获异常,创建一个有意义的对话框来解释错误并返回到主tk循环。例如:很难确定字符串是否是有效的电子邮件地址。既然你没有使用它,如果你告诉他们它是无效的,你很可能是错的。你知道吗
相关问题 更多 >
编程相关推荐