2

I use raise function in python 2.7 as a way to stop further code being executed, without exiting, when a condition is not met. This is shown in example below:

from Tkinter import *
import tkMessageBox

def foo():
    a = 3
    if a == 2:
        tkMessageBox.showinfo('Hello', 'Yup yup yup')
    else:
        tkMessageBox.showinfo('Hello', 'My bad!')
        raise

    tkMessageBox.showinfo('Further code' ,"You shouldn't see me if a is not 2")

app = Tk()
app.title("ABC")
app.geometry()


filetype_fasta = [('fasta files', '*.fasta'), ('All files', '*.*')]
button_templ = Button(app, text = 'Click me', width =6, command = foo)
button_templ.grid(row = 3, column = 2)

app.mainloop()

It works fine for a complicated script I have. My question is this - Is there any potential problem, that I should be aware of, in using raise this way? If yes, is there a better/common method to do the same thing?

Edit: Example changed to demonstrate the idea better.

4

1 回答 1

4

“raise”语句会引发的最大问题是缺乏沟通。使用 raise 时,最好为使用 raise 的函数添加一个 doc 字符串(即,函数/方法在什么条件下会抛出错误,错误/原因是什么等)。

另请注意,调用函数(foo在您的示例中调用该方法的函数)需要有一个正确的异常来处理引发。甚至少数程序员实际上使用 raise 语句来防止在整个代码中出现多个 return 语句。但是,在这些情况下,加薪将在相同的方法/函数中处理。

为了更好地看待事情(为了新程序员或刚搬到您项目的程序员),您可以创建自定义异常并在适当的位置引发它们,而不仅仅是给出引发语句。正如 Joran Beasley 在评论中提到的那样,使用 raise 绝对没有错。除了使用 raise 语句来打破流程之外应该有一个目的。

准确地说,使用 raise 语句不会有任何问题。但是,如果您要使用 raise 语句,请遵循一些礼貌,这会使维护代码的人的生活变得更简单。

于 2015-02-11T07:39:36.983 回答