Reputation: 16152
Is there a way to prevent the rest of a try block from executing if an exception is executed? Say for example I've run out of ingredient 1
, how do I prevent the rest of the try block from executing once that exception is executed?
try:
#add ingredient 1
#add ingredient 2
#add ingredient 3
except MissingIngredient:
print 'you are missing ingredients'
Upvotes: 0
Views: 79
Reputation: 15367
Use another try/catch block in the original try block.
try:
#add ingredient 1
#add ingredient 2
#add ingredient 3
except MissingIngredient:
try:
....
except MissingIngredient:
....
print 'you are missing ingredients'
However, possibly the following structure is better:
try:
#add ingredient 1
try:
#add ingredient 2
try:
#add ingredient 3
# Here you can assume ingredients 1, 2 and 3 are available.
except MissingIngredient:
# Here you know ingredient 3 is missing
except MissingIngredient:
# Here you know ingredient 2 is missing
except MissingIngredient:
# Here you know ingredient 1 is missing
Upvotes: 0
Reputation: 1258
It happens automatically:
class MissingIngredient(Exception):
pass
def add_ingredient(name):
print 'add_ingredient',name
raise MissingIngredient
try:
add_ingredient(1)
add_ingredient(2)
add_ingredient(3)
except MissingIngredient:
print 'you are missing ingredients'
The rest of the try block will not be executed if one of its expression raises exception. It will print:
add_ingredient 1
you are missing ingredients
Upvotes: 5
Reputation: 326
It doesn't. It should immediately pull out of the try block to the except clause; the only way I know of to keep going is some kind of try... except... finally...
Upvotes: 0