Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting out of a function in Python

I want to get out of a function when an exception occurs or so. I want to use other method than 'return'

like image 526
user46646 Avatar asked Jan 15 '09 13:01

user46646


People also ask

How do you exit a function?

Using return is the easiest way to exit a function. You can use return by itself or even return a value.

What keyword is used to exit a function Python?

The return keyword is to exit a function and return a value.


2 Answers

Assuming you want to "stop" execution inside of that method. There's a few things you can do.

  1. Don't catch the exception. This will return control to the method that called it in the first place. You can then do whatever you want with it.
  2. sys.exit(0) This one actually exits the entire program.
  3. return I know you said you don't want return, but hear me out. Return is useful, because based on the value you return, it would be a good way to let your users know what went wrong.
like image 167
Anton Avatar answered Oct 12 '22 12:10

Anton


If you catch an exception and then want to rethrow it, this pattern is pretty simple:

try:
    do_something_dangerous()
except:
    do_something_to_apologize()
    raise

Of course if you want to raise the exception in the first place, that's easy, too:

def do_something_dangerous(self):
    raise Exception("Boo!")

If that's not what you wanted, please provide more information!

like image 38
Michael Haren Avatar answered Oct 12 '22 12:10

Michael Haren