This is a script that utilizes lazy exception throwing. What I do is decorate a function that might throw an exception to throw an exception with a formatted string.
from functools import wraps
def on_fail(message):
def on_fail_dec(func):
@wraps(func)
def on_fail_wrapper(*args, **kw):
ret = None
success = True
message_addon = ""
try:
ret = func(*args, **kw)
except Exception as e:
success = False
message_addon = str(e)
# raise Exception if failed
if not success:
raise Exception("{0}\nBecause: {1}".format(message, message_addon))
return ret
return on_fail_wrapper
return on_fail_dec
# Usage :
@on_fail("Division Failed")
def divide(a, b):
return a / b
test_cases = [(1, 2), (20, 5), (3, 0)]
for a,b in test_cases:
print("Trying to divide {0} from {1}".format(a, b))
print(divide(a, b))
Output:
Trying to divide 1 from 2 0.5 Trying to divide 20 from 5 4.0 Trying to divide 3 from 0 Traceback (most recent call last): File "<string>", line 30, in <module> File "<string>", line 16, in on_fail_wrapper Exception: Division Failed Because: division by zero