【发布时间】:2021-12-06 07:06:48
【问题描述】:
将def clockPrint() 函数放入try-except 时,try 块工作正常,但 except 块不工作(将语句打印为在 except 块中的输出)
import datetime
try:
def clockPrint(sentence):
now = datetime.datetime.now()
date_time = now.strftime("%H:%M:%S")
print(date_time + " : " + sentence)
except TypeError:
print("Error: Invalid sentence")
如果我尝试调用clockPrint(909),那么根据逻辑,它应该显示“Error: Invalid sentence”作为输出,但它显示“TypeError: can only concatenate str (not "int") to str”作为输出。任何建议
【问题讨论】:
-
为什么try 在函数之外?您只会在定义函数时捕获错误,而不是在调用它时捕获错误。
标签: python function try-except