英文:
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)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论