PYTHON Reference Guide
Revision Time: 3 mins

Exception Handling Reference

Try, except, else, and finally blocks flow control.

try-except-else
Return: None

Execute a block of code ONLY if no exceptions were raised inside the try block.

Used In: Confirming API responses parsing before saving values.

Syntax signature:try: ... except: ... else: ...
Code snippet:
python
try:
    data = 'clean_data'
except ValueError:
    print('error')
else:
    print(data)
Expected Output:clean_data

Time Complexity: O(1)

Related Methods: try-except-finally

Remember: Prevents accidental catching of exceptions that might occur inside the else block itself.
try-except-finally
Return: None

Execute a cleanup block regardless of whether exceptions were raised, handled, or unhandled.

Used In: Releasing connection pool locks in pipelines.

Syntax signature:try: ... except: ... finally: ...
Code snippet:
python
try:
    1 / 0
except:
    print('error')
finally:
    print('cleanup')
Expected Output:error cleanup

Time Complexity: O(1)

Related Methods: try-except-else

Remember: Excellent for releasing locks or closing database connections, even if unhandled errors occurred.
raise Statement
Return: None

Manually trigger an exception.

Used In: Halting pipelines if data quality schemas fail.

Syntax signature:raise ValueError('Custom msg')
Code snippet:
python
try:
    raise ValueError('OOM Alert')
except ValueError as e:
    print(e)
Expected Output:OOM Alert

Time Complexity: O(1)

Related Methods: raise ... from ...

Remember: Pass meaningful messages to assist diagnostics in log files.
Custom Exceptions
Return: None

Define domain-specific custom exception classes by inheriting from Exception.

Used In: Validating custom ETL validation rules.

Syntax signature:class MyError(Exception):
Code snippet:
python
class SchemaError(Exception): pass
try:
    raise SchemaError('Missing column')
except SchemaError as e:
    print(e)
Expected Output:Missing column

Time Complexity: O(1)

Remember: Always inherit from standard Exception, not BaseException (which is reserved for exit calls).
Multiple Exception Handling
Return: None

Handle multiple distinct exception types in a single except statement or separate blocks.

Used In: Catching varied file parsing errors.

Syntax signature:except (ValueError, TypeError) as e:
Code snippet:
python
try:
    int('abc')
except (ValueError, TypeError) as e:
    print('Invalid format')
Expected Output:Invalid format

Time Complexity: O(1)

Remember: Order except blocks from most specific subclasses to most general classes.
Exception Chaining
Return: None

Explicitly link a caught exception to a new exception to maintain traceback history.

Used In: Translating lower-level library errors to domain exceptions.

Syntax signature:raise NewException() from original_error
Code snippet:
python
try:
    int('abc')
except ValueError as e:
    try:
        raise KeyError('Data error') from e
    except KeyError as k:
        print(repr(k.__cause__))
Expected Output:ValueError("invalid literal for int() with base 10: 'abc'")

Time Complexity: O(1)

Remember: Populates the __cause__ attribute on the new exception, keeping tracebacks complete.
Common Built-in Exceptions
Return: None

List standard built-in exception types and when they are raised.

Used In: Defensive validations, API inputs handling.

Syntax signature:except KeyError / ValueError / TypeError / IndexError / FileNotFoundError / ZeroDivisionError
Code snippet:
python
d = {'a': 1}
try:
    print(d['b'])
except KeyError:
    print('Key missing')
Expected Output:Key missing

Time Complexity: O(1)

Remember: Familiarize yourself with these types to raise the most semantically correct exception.