Exception handling¶
Avoid exception handling in conversions as long as possible, because it reduces clarity and can hide issues in the code.
c.try_¶
Experimental feature
It was added on Feb 21, 2024 and may be stabilized ~ in half a year.
c.try_(conv).except_(exc_def, value, re_raise_if=None)
conversion
wrapper allows to handle exceptions:
conv
: a conversion, which is expected to raise an exceptionexc_def
: exception class or tuple of exception classes to be caughtre_raise_if
(optional): if it evaluates to true, the caught exception is re-raised
from convtools import conversion as c
converter = (
c.iter(
c.try_(c.item(0) / c.item(1))
.except_(ZeroDivisionError, value=c.this, re_raise_if=c.item(0) == 0)
.except_(TypeError, None)
)
.as_type(list)
.gen_converter(debug=True)
)
assert converter([(1, 2), (3, 0), (4, "abc")]) == [0.5, (3, 0), None]
def except_(data_):
try:
return data_[0] / data_[1]
except ZeroDivisionError as exc_:
if data_[0] == 0:
raise
return data_
except TypeError as exc_:
return None
def converter(data_):
try:
return [except_(i) for i in data_]
except __exceptions_to_dump_sources:
__convtools__code_storage.dump_sources()
raise