tryexcept#
- class tryexcept(die=None, catch=None, verbose=1, history=None)[source]#
Bases:
suppress
Simple class to catch exceptions in a single line
Effectively an alias to
contextlib.suppress()
, which itself is a programmatic equivalent to using try-except blocks.By default, all errors are caught. If
catch
is not None, then by default raise all other exceptions; ifdie
is an exception (list of exceptions, then by default suppress all other exceptions.Due to Python’s fundamental architecture, exceptions can only be caught inside a with statement, and the with block will exit immediately as soon as the first exception is encountered.
- Parameters:
die (bool/exception) – default behavior of whether to raise caught exceptions
catch (exception) – one or more exceptions to catch regardless of “die”
verbose (bool) – whether to print caught exceptions (0 = silent, 1 = error type, 2 = full error information)
history (list/tryexcept) – a
tryexcept
object, or a list of exceptions, to keep the history (see example below)
Examples:
# Basic usage values = [0,1] with sc.tryexcept(): # Equivalent to contextlib.suppress(Exception) values[2] # Raise only certain errors with sc.tryexcept(die=IndexError): # Catch everything except IndexError values[2] # Catch (do not raise) only certain errors, and print full error information with sc.tryexcept(catch=IndexError, verbose=2): # Raise everything except IndexError values[2] # Storing the history of multiple exceptions tryexc = None for i in range(5): with sc.tryexcept(history=tryexc) as tryexc: print(values[i]) tryexc.traceback()
New in version 2.1.0.New in version 3.0.0: renamed “print” to “traceback”; added “to_df” and “disp” optionsNew in version 3.1.0: renamed “exceptions” to “data”; added “exceptions” propertyAttributes
Whether or not any exceptions were encountered
Retrieve the last exception, if any
Retrieve the last exception, if any
Methods
- traceback(which=None, tostring=False)[source]#
Print the exception (usually the last)
- Parameters:
which (int/list) – which exception(s) to print; if None, print all
tostring (bool) – whether to return as a string (otherwise print)
New in version 3.1.0: optionally print multiple tracebacks
- property exceptions#
Retrieve the last exception, if any
- property exception#
Retrieve the last exception, if any
- property died#
Whether or not any exceptions were encountered