myko__
myko__

Reputation: 1

try/except doesn't catch TypeError in Python

I'm quite new at Python, so forgive me if my question is silly, however, I cannot understand what's the difference between two functions below and why the second one works when exception is used and the fist one doesn't. I tried swapping 'result' with 'return' but it doesn't help. I was thinking that my condition for missing argument is incorrect but even if I remove it and leave only return 'month missing', the exception is still not printed.

Thanks for your help.

def after_n_months(year, month):
    try:
        result year + (month // 12) 
    except TypeError:
        return 'month missing' if month is None else 'year missing' 
print(after_n_months( 2000, ))


def divide(x, y):
    try:
        result = x / y
    except ZeroDivisionError:
        return "division by zero!"
print(divide(2,0))

Upvotes: 0

Views: 1918

Answers (1)

thomaslecouffe
thomaslecouffe

Reputation: 142

It's because TypeError exception is catch before you enter in the function.

Try this instead

def after_n_months(year, month):
    return year + (month // 12) 

try : 
    print(after_n_months(2000))
except:
    print("error")

EDIT : To test your function you can also put into None

def after_n_months(year, month):
    try:
        return year + (month // 12) 
    except TypeError:
        return 'month missing' if month is None else 'year missing' 
    print(after_n_months( 2000 ))

print(after_n_months(2000, None))
print(after_n_months(None, 12))

EDIT2: You can also put your function inputs in None, like this and remove the expections, because it's not needed.

def after_n_months(year = None, month = None):
        if year is None:
            print("Year missing")
            return None
        if month is None:
            print("Month is missing")
            return None
        return year + (month // 12) 

after_n_months(5,12)
after_n_months(year=5)
after_n_months(month=12)

Upvotes: 1

Related Questions