What error to use to trigger except Exception:

def compare(a = None, b = None, c = None):
try:
value = False
a = int(a)
b = int(b)
c = int(c)
print(“Valid values.”)
if a == b or a == c or b == c:
value = True
except ValueError:
print(“ValueError: Only, numbers are allowed.”)
except TypeError:
print(“TypeError: Please enter only numbers.”)
except Exception:
print(Exception)
print(“Exception, Only numbers are allowed!”)
finally:
print("Values ", a, b, c)
return value

all integers

print(“Result: “,compare(1, 2, 3))
print(”\n”)

numbers in str

print(“Result: “,compare(“2”, “3”, “4”))
print(”\n”)

1 Like

Hi
It’ll be helpful if you can post within backticks so your code is tab-delineated e.g. where does this sit? Inside the final Exception condition or outside?

Also knowing how the tabs work makes it not just more readable but easier for you to spot bugs.

Secondly the question is unclear: trigger which Exception? The code as it is will trigger Exceptions. The final ‘except Exception’ will work but won’t print what you want. Instead try:

except Exception as e:
    print(e) # to see why that exception was triggered or
    print("some customised message you like")

In “as e” that e is just a convention: e can be any string.