我的尝试除了在函数外部不起作用。

huangapple go评论66阅读模式
英文:

My try exept not working outside the function

问题

我在捕获错误,如果发生错误,然后执行异常代码。但它不执行异常代码。

fruits = ["Apple", "Pear", "Orange"]

#TODO: 捕获异常并确保代码运行而不崩溃。

try:
    def make_pie(index):
        fruit = fruits[index]
        print(fruit + " pie")
except:
    print("Fruit pie")

make_pie(4)
英文:

i was catching error if error occurs then implement the except code. but it is not executing except code

fruits = ["Apple", "Pear", "Orange"]

#TODO: Catch the exception and make sure the code runs without crashing.

try:
    def make_pie(index):
        fruit = fruits[index]
        print(fruit + " pie")
except:
    print("Fruit pie")

make_pie(4)

答案1

得分: 1

你试图在函数被定义时捕获异常,而不是在它被调用时。

fruits = ["Apple", "Pear", "Orange"]

def make_pie(index):
    fruit = fruits[index]
    print(fruit + " pie")

try:
    make_pie(4)
except KeyError:
    print("水果派")

或者,你想在函数内部使用try语句。

fruits = ["Apple", "Pear", "Orange"]

def make_pie(index):
    try:
        fruit = fruits[index]
    except KeyError:
        fruit = "水果"

    print(fruit + " pie")

make_pie(4)
英文:

You are trying to catch an exception when the function is defined, rather than when it is called.

fruits = ["Apple", "Pear", "Orange"]

def make_pie(index):
    fruit = fruits[index]
    print(fruit + " pie")

try:
    make_pie(4)
except KeyError:
    print("Fruit pie")

Or, you want the try statement inside the function.

fruits = ["Apple", "Pear", "Orange"]

def make_pie(index):
    try:
        fruit = fruits[index]
    except KeyError:
        fruit = "Fruit"

    print(fruit + " pie")

make_pie(4)

答案2

得分: 0

你只在函数定义中使用了try,你必须在函数内部使用try catch。

fruits = ["Apple", "Pear", "Orange"]

def make_pie(index):
    try:
        fruit = fruits[index]
        print(fruit + " pie")
    except:
        print("Fruit pie")

make_pie(4)
英文:

you are only using try on defining the function, you must try catch inside the function.

fruits = ["Apple", "Pear", "Orange"]

def make_pie(index):
    try:
        fruit = fruits[index]
        print(fruit + " pie")
    except:
        print("Fruit pie")

make_pie(4)

huangapple
  • 本文由 发表于 2023年2月23日 22:55:39
  • 转载请务必保留本文链接:https://go.coder-hub.com/75546503.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定