Reputation: 159
I want to raise an error and then return a value.
raise ValueError('Max Iter Reached')
return x
And make both lines work.
Now I found this question is stupid and I decided to print an error message.
print 'Max Iter Reached'
return x
Upvotes: 2
Views: 5864
Reputation: 33335
This is impossible. A function can either return a value or raise an exception. It cannot do both. Calling return
or raise
will absolutely terminate the function.
You could encode a return value inside the exception message, like this:
raise SomeException('my value is 5')
Or you could return a tuple of an exception and a value:
return (SomeException('hello'), 5)
Upvotes: 6
Reputation: 22697
It does not make sense but In case you need it.
def your_method(self):
......
try:
raise ValueError('Max Iter Reached')
except ValueError as e:
return value
Upvotes: 3