A context manager that will catch certain exceptions and provide an indication they occurred. >>> with ExceptionTrap() as trap: ... raise Exception() >>> bool(trap) True >>> with ExceptionTrap() as trap: ... pass >>> bool(trap) False >>> with E
| 6 | |
| 7 | # from jaraco.context 6.1 |
| 8 | class ExceptionTrap: |
| 9 | """ |
| 10 | A context manager that will catch certain exceptions and provide an |
| 11 | indication they occurred. |
| 12 | |
| 13 | >>> with ExceptionTrap() as trap: |
| 14 | ... raise Exception() |
| 15 | >>> bool(trap) |
| 16 | True |
| 17 | |
| 18 | >>> with ExceptionTrap() as trap: |
| 19 | ... pass |
| 20 | >>> bool(trap) |
| 21 | False |
| 22 | |
| 23 | >>> with ExceptionTrap(ValueError) as trap: |
| 24 | ... raise ValueError("1 + 1 is not 3") |
| 25 | >>> bool(trap) |
| 26 | True |
| 27 | >>> trap.value |
| 28 | ValueError('1 + 1 is not 3') |
| 29 | >>> trap.tb |
| 30 | <traceback object at ...> |
| 31 | |
| 32 | >>> with ExceptionTrap(ValueError) as trap: |
| 33 | ... raise Exception() |
| 34 | Traceback (most recent call last): |
| 35 | ... |
| 36 | Exception |
| 37 | |
| 38 | >>> bool(trap) |
| 39 | False |
| 40 | """ |
| 41 | |
| 42 | exc_info = None, None, None |
| 43 | |
| 44 | def __init__(self, exceptions=(Exception,)): |
| 45 | self.exceptions = exceptions |
| 46 | |
| 47 | def __enter__(self): |
| 48 | return self |
| 49 | |
| 50 | @property |
| 51 | def type(self): |
| 52 | return self.exc_info[0] |
| 53 | |
| 54 | @property |
| 55 | def value(self): |
| 56 | return self.exc_info[1] |
| 57 | |
| 58 | @property |
| 59 | def tb(self): |
| 60 | return self.exc_info[2] |
| 61 | |
| 62 | def __exit__(self, *exc_info): |
| 63 | type = exc_info[0] |
| 64 | matches = type and issubclass(type, self.exceptions) |
| 65 | if matches: |
no outgoing calls
no test coverage detected
searching dependent graphs…