Home > front end >  why my function is not working for except block?
why my function is not working for except block?

Time:12-06

While putting the 'def clockPrint' function in try-except, try block is working fine but except block is not working (printing the statement as output which is in except block)

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

If I try to call clockPrint(909) then according to the logic, it should display "Error: Invalid sentence" as an output but it is displaying "TypeError: can only concatenate str (not "int") to str" as an output. Any suggestions

CodePudding user response:

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

CodePudding user response:

Try this:

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

CodePudding user response:

You try block just does nothing. Define function outside try block and just call it from this block.

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