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; if die 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.print()
New in version 2.1.0.
New in version 3.0.0: renamed “print” to “traceback”; added “to_df” and “disp” options

Attributes

died

Methods

traceback(which=-1)[source]#

Print the exception (usually the last)

to_df()[source]#

Convert the exceptions to a dataframe

disp()[source]#

Display all exceptions as a table