Using raise function to stop execution of further code in python after an error

Manavalan Gajapathy picture Manavalan Gajapathy · Feb 11, 2015 · Viewed 8.4k times · Source

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.

Answer

thiruvenkadam picture thiruvenkadam · Feb 11, 2015

The biggest problem that would raise with the 'raise' statement is the lack of communication. When you use raise, you better add a doc string for the function in which raise is used(that is, for what conditions the function/method would throw an error, what are the errors/cause and so on).

Also be aware that the calling function(the function that calls the method foo in your example) needs to have an except properly to handle the raise. Even a few coders actually use raise statement to prevent multiple return statements throughout the code. However, the raise will be handled in the same method/function in those cases.

To put things in a better perspective(for the sake of a new programmer or the programmer who just moved to your project), you can create custom exceptions and raise them at appropriate places rather than just giving a raise statement. As Joran Beasley mentioned in the comments, there's absolutely nothing wrong with using raise. Except that there should be a purpose more than just break the flow with using raise statement.

To be precise, there won't be any problem as such with using a raise statement. However, if you are going to use raise statement, do follow a few courtesies that makes the life of the one maintaining the code simpler.