xoutil.eight.exceptions
- Exceptions handling compatibility¶
Solve compatibility issues for exceptions handling.
Python 2 defines a module named exceptions but Python 3 doesn’t. We decided
not to implement something similar, for example, in xoutil.future
package because all these exception classes are built-ins in both Python major
versions, so use any of them directly; nevertheless StandardError
is
undefined in Python 3, we introduce some adjustments here in base classes
(BaseException
and StandardError
classes).
The functions catch()
and throw()
unify syntax differences raising
exceptions. In Python 2 the syntax for raise
is:
"raise" [type ["," value ["," traceback]]]
and in Python 3:
"raise" [error[.with_traceback(traceback)] ["from" cause]]
You can use catch()
as a function to wrap errors going to be raised with
a homogeneous syntax using a trace extra argument:
>>> divisor = 0
>>> try:
... inverted = 1/divisor
... except Exception:
... raise catch(ValueError('Invalid divisor.'))
If you want to be completely compatible raising exceptions with trace-backs,
use the throw()
function instead the raise
statement.
-
xoutil.eight.exceptions.
catch
(self)[source]¶ Check an error to settle trace-back information if found.
Parameters: self – The exception to check.
-
xoutil.eight.exceptions.
caught
= <xoutil.tasking.AutoLocal object>¶ Last caught trace context, see
catch()
.
-
xoutil.eight.exceptions.
grab
(self=None, trace=None)[source]¶ Prepare an error being raised with a trace-back and/or a cause.
Parameters: - self – The exception to be raised or None to capture the current trace context for future use.
- trace – Could be a trace-back, a cause (exception instance), or both
in a tuple (or list) with
(cause, traceback)
. If None, use the current system exception info as the trace (seesys.exc_info()
built-in function).
This function create a syntax for
raise
statement, compatible for both major Python versions.
-
xoutil.eight.exceptions.
throw
(error, tb=None)[source]¶ Unify syntax for raising an error with trace-back information.
Instead of using the Python
raise
statement, usethrow(error, tb)
. If tb argument is not given, the trace-back information is looked up in the context.
-
xoutil.eight.exceptions.
traceof
(error)[source]¶ Get the trace-back information of the given error.
Return None if not defined.