Python 如果执行异常,是否有方法阻止执行try块?

Python 如果执行异常,是否有方法阻止执行try块?,python,Python,如果执行异常,是否有方法阻止try块的其余部分执行?例如,假设我用完了成分1,那么在执行该异常后,如何防止try块的其余部分执行 try: #add ingredient 1 #add ingredient 2 #add ingredient 3 except MissingIngredient: print 'you are missing ingredients' 在原始try块中使用另一个try/catch块 try: #add ingredien

如果执行异常,是否有方法阻止try块的其余部分执行?例如,假设我用完了
成分1
,那么在执行该异常后,如何防止try块的其余部分执行

try:
    #add ingredient 1
    #add ingredient 2
    #add ingredient 3
except MissingIngredient:
    print 'you are missing ingredients'

在原始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

在原始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

没有。应立即将其从试块中拉出至except子句;我所知道的保持下去的唯一方法就是尝试。。。除了最后…

它没有。应立即将其从试块中拉出至except子句;我所知道的保持下去的唯一方法就是尝试。。。除了最后…

它会自动发生:

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块的某个表达式引发异常,则不会执行try块的其余部分。它将打印:

add_ingredient 1
you are missing ingredients

它会自动发生:

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块的某个表达式引发异常,则不会执行try块的其余部分。它将打印:

add_ingredient 1
you are missing ingredients

你不需要做任何事。如果在
add component 1
中抛出异常,则不会执行其他两个异常,您无需执行任何操作。如果在
add component 1
中抛出异常,则不会执行其他两个异常。这不是问题的答案。这不是问题的答案。