如果执行异常,有没有办法阻止try块的其余部分执行?比方说,我已经用完了ingredient 1
,如果执行该异常,如何防止执行块的其余部分执行?
try:
#add ingredient 1
#add ingredient 2
#add ingredient 3
except MissingIngredient:
print 'you are missing ingredients'
答案 0 :(得分:4)
它会自动发生:
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'
如果其中一个表达式引发异常,则不会执行其余的try块。它会打印出来:
add_ingredient 1
you are missing ingredients
答案 1 :(得分:0)
在原始try块中使用另一个try / catch块。
try:
#add ingredient 1
#add ingredient 2
#add ingredient 3
except MissingIngredient:
try:
....
except MissingIngredient:
....
print 'you are missing ingredients'
但是,可能以下结构更好:
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
答案 2 :(得分:0)
没有。它应该立即从try块中拉出到except子句;我知道继续前进的唯一方法是尝试......除了......最后......