TLDR: Move the exception handler into the function, where the exception actually occurs:
def di(a, b):
try:
return a/b
except ZeroDivisionError:
print("Divide by 0 Error")
Function definitions in Python are executed, and this execution can have side-effects -- such as modifying objects or raising exception. However, on definition only the function signature is run immediately; the body is stored and only run when the function is called.
>>> def func(arg=print("default evaluated")):
... print("body evaluated")
...
default evaluated
>>> func
<function __main__.func(arg=None)>
>>> func()
body evaluated
When you define a function inside an exception handler, this exception handler only receives exceptions raised from evaluating the signature. For example, computing a default argument may raise a ZeroDivisionError:
>>> def invalid_def(arg=10/0):
... pass
...
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ZeroDivisionError: division by zero
An exception handler for this case is rarely what you want. It can be useful to conditionally define a function, e.g. if a NameError indicates a dependency is not available.
Commonly you want to handle an exception originating in the body of a function. These are raised whenever the function is actually called:
>>> def invalid_call():
... return 10 / 0
...
>>> invalid_call()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 1, in invalid_call
ZeroDivisionError: division by zero
>>> invalid_call()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 1, in invalid_call
ZeroDivisionError: division by zero
There are two ways to handle such exceptions: externally or internally.
External handling requires an exception handler at each call site. This is more flexible but requires boilerplate, since it requires an exception handler for each call.
>>> try:
... invalid_call()
... except ZeroDivisionError:
... print("suppressed an external error")
Internal handling requires an exception handler in the body. This is less flexible but needs no boilerplate, since one exception handler covers all cases.
>>> def valid_call():
... try:
... return 10 / 0
... except ZeroDivisionError:
... print("suppressed an internal error")
Both approaches are valid; which to select depends on whether you rather need usability or re-usability. Notably, it is not uncommon to combine both approaches: an internal handler generalises the exception, and external handler expects only general exceptions.
For example, in your case that would allow to handle multiple operations:
def div(a, b):
try:
return a / b
# convert operation-specific exception to general one
except ZeroDivisionError:
raise ValueError("Cannot divide by 0")
# may be another operation -- add, mul, sub, ...
operation = div
try:
operation(10, 0)
# only handle exception general to all operations
except ValueError as err:
print("Invalid values: %s" % err)
raisewithprint. Useraiseif you wanto raise an exception. Notprint.printprints things.raiseraises exceptions. - smci