I want to get out of a function when an exception occurs or so. I want to use other method than 'return'
Help in this.
I want to get out of a function when an exception occurs or so. I want to use other method than 'return'
Help in this.
Can't think of another way to "get out" of a function other than a) return, b) throw an exception, or c) terminate execution of the program.
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!
The exception itself will terminate the function:
def f():
a = 1 / 0 # will raise an exception
return a
try:
f()
except:
print 'no longer in f()'
Assuming you want to "stop" execution inside of that method. There's a few things you can do.
As others have pointed out, an exception will get you out of the method. You shouldn't be ashamed or embarassed by exceptions; an exception indicates an error, but that's not necessarily the same as a bug.
For example, say I'm writing a factorial function. Factorial isn't defined for negative numbers, so I might do this:
def factorial(n):
if n < 0:
raise ValueError
if n == 0:
return 1
return n*factorial(n-1)
I would then look for the exception:
n = raw_input('Enter a number.')
try:
print factorial(n)
except ValueError:
print 'You entered a negative number.'
I can make the exception more informative than a ValueError by defining my own:
class NegativeInputError(Exception):
pass
# in the function:
if n < 0:
raise NegativeInputError
HTH!