TL;DR: Why are my exceptions triggering only in certain situations, despite the fact that it is the same error?
The code successfully catches a NameError with an all numerical argument. So if someone mistakenly inputs a number instead of an operator, it gives them the correct exception error message. However, my code fails to catch other exceptions, and I'm unsure why.
For example:
print(better_calc(5, 5, 5))
This returns the desired exception message of
5 5 5 = Error: Name error. Please check your input
However, it does not catch other errors. Instead, it terminates the programme. For example,
print(better_calc(5, g, 5))
This returns ''NameError: name 'g' is not defined'', without triggering the exception or the exception message.
Similarly
print(better_calc(5, *, 5))
This returns ''SyntaxError: invalid syntax'', without triggering the exception or the exception message.
I realize that if I included quotation marks on the operator, that the code would work, however, my goal is to trigger the exceptions.
def better_calc(num1, op, num2):
try:
if op == "+":
result = num1+num2
elif op == "-":
result = num1-num2
elif op == "*":
result = num1*num2
elif op == "/":
num1/num2
except NameError:
print(f"Error: Name error. Please check your input")
except UnboundLocalError:
print(f"Error: Value error. Please check your input")
except SyntaxError:
print(f"Error: Syntax Error. Please check your input")
print(num1, op, num2, "=")
return result
print(better_calc(5, 5, 5))