【问题标题】:why my function is not working for except block?为什么我的功能不适用于除块?
【发布时间】: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


【解决方案1】:

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")

【讨论】:

    【解决方案2】:
    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")
    

    【讨论】:

      【解决方案3】:

      试试这个:

      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")  
      

      【讨论】:

        猜你喜欢
        • 2022-01-07
        • 2015-08-01
        • 1970-01-01
        • 2017-04-15
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多