为什么我的功能不适用于 except 块?
why my function is not working for except block?
将 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
”作为输出。有什么建议
import datetime
def clockPrint(sentence):
try:
now = datetime.datetime.now()
date_time = now.strftime("%H:%M:%S")
print(date_time + " : " + sentence)
except TypeError:
print("Error: Invalid sentence")
试试这个:
import datetime
def clockPrint(sentence):
now = datetime.datetime.now()
date_time = now.strftime("%H:%M:%S")
try:
print(date_time + " : " + sentence)
except TypeError:
print("Error: Invalid sentence")
你 try
块什么都不做。在 try
块外定义函数,然后从该块调用它。
import datetime
def clockPrint(sentence):
now = datetime.datetime.now()
date_time = now.strftime("%H:%M:%S")
print(date_time + " : " + sentence)
try:
...
clockPrint(sentence)
...
except TypeError:
print("Error: Invalid sentence")
将 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
”作为输出。有什么建议
import datetime
def clockPrint(sentence):
try:
now = datetime.datetime.now()
date_time = now.strftime("%H:%M:%S")
print(date_time + " : " + sentence)
except TypeError:
print("Error: Invalid sentence")
试试这个:
import datetime
def clockPrint(sentence):
now = datetime.datetime.now()
date_time = now.strftime("%H:%M:%S")
try:
print(date_time + " : " + sentence)
except TypeError:
print("Error: Invalid sentence")
你 try
块什么都不做。在 try
块外定义函数,然后从该块调用它。
import datetime
def clockPrint(sentence):
now = datetime.datetime.now()
date_time = now.strftime("%H:%M:%S")
print(date_time + " : " + sentence)
try:
...
clockPrint(sentence)
...
except TypeError:
print("Error: Invalid sentence")