This is a weird requirement because the function always returns None
, because num
is a local variable and the function does not return it. So you can't even figure out that there was an exception by having a global variable num
without adding a global
statement to the function.
This approach will work, though I have a poor opinion of the question:
def zero(a, b):
try:
num = a / b
except:
print("cannot divide by zero")
def print(error):
raise ValueError(error)
>>> zero(10,5)
>>> zero(10,0)
Traceback (most recent call last):
File "<pyshell#1>", line 3, in zero
num = a / b
ZeroDivisionError: division by zero
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "<pyshell#13>", line 1, in <module>
zero(10,0)
File "<pyshell#1>", line 5, in zero
print("cannot divide by zero")
File "<pyshell#11>", line 2, in print
raise ValueError(error)
ValueError: cannot divide by zero
The function zero()
is very poorly coded, and forcing you to use it unchanged has little educational benefit that I can see, except maybe to drive home the point that bare except
clauses are a bad idea.
This answer is similar in spirit to @buran's answer. They both involve changing the behaviour of print()
to deliver the information you want outside of the function.