views:

394

answers:

6

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.

+3  A: 

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.

lc
Class c) is a subclass of b): raise SystemExit
J.F. Sebastian
I was referring more to terminating the process (manually from outside the program?). Good point though.
lc
+12  A: 

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!

Michael Haren
A: 

Are you looking for yield?

Nikron
+3  A: 

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()'
unbeknown
Right, one would certainly imagine so. Which leads me to ask what the original question is /really/ asking for...
lc
+2  A: 

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.
Anton
A: 

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!

John Fouhy