Exception Handling Reference
Try, except, else, and finally blocks flow control.
Execute a block of code ONLY if no exceptions were raised inside the try block.
Used In: Confirming API responses parsing before saving values.
try: ... except: ... else: ...try:
data = 'clean_data'
except ValueError:
print('error')
else:
print(data)clean_dataTime Complexity: O(1)
Related Methods: try-except-finally
Execute a cleanup block regardless of whether exceptions were raised, handled, or unhandled.
Used In: Releasing connection pool locks in pipelines.
try: ... except: ... finally: ...try:
1 / 0
except:
print('error')
finally:
print('cleanup')error
cleanupTime Complexity: O(1)
Related Methods: try-except-else
Manually trigger an exception.
Used In: Halting pipelines if data quality schemas fail.
raise ValueError('Custom msg')try:
raise ValueError('OOM Alert')
except ValueError as e:
print(e)OOM AlertTime Complexity: O(1)
Related Methods: raise ... from ...
Define domain-specific custom exception classes by inheriting from Exception.
Used In: Validating custom ETL validation rules.
class MyError(Exception):class SchemaError(Exception): pass
try:
raise SchemaError('Missing column')
except SchemaError as e:
print(e)Missing columnTime Complexity: O(1)
Handle multiple distinct exception types in a single except statement or separate blocks.
Used In: Catching varied file parsing errors.
except (ValueError, TypeError) as e:try:
int('abc')
except (ValueError, TypeError) as e:
print('Invalid format')Invalid formatTime Complexity: O(1)
Explicitly link a caught exception to a new exception to maintain traceback history.
Used In: Translating lower-level library errors to domain exceptions.
raise NewException() from original_errortry:
int('abc')
except ValueError as e:
try:
raise KeyError('Data error') from e
except KeyError as k:
print(repr(k.__cause__))ValueError("invalid literal for int() with base 10: 'abc'")Time Complexity: O(1)
List standard built-in exception types and when they are raised.
Used In: Defensive validations, API inputs handling.
except KeyError / ValueError / TypeError / IndexError / FileNotFoundError / ZeroDivisionErrord = {'a': 1}
try:
print(d['b'])
except KeyError:
print('Key missing')Key missingTime Complexity: O(1)