Exception Handling

Code Properties

  • Language: Python
  • Concept: Error Handling

Overview

Sources:

Python exception handling with custom exception classes and proper ordering of except blocks.

Code

class Ex_Base(BaseException):
    pass
 
class Ex_Deriv(Ex_Base):
    pass
 
# correct order: catch more specific exception first
try:
    print('Before raising the exception')
    raise Ex_Deriv()
    print('After raising the exception')
 
except Ex_Deriv as e:
    print('Ex_Deriv caught')  # this will be caught
 
except Ex_Base as e:
    print('Ex_Base caught')
 
 
# wrong order: base class catches first
try:
    print('Before raising the exception')
    raise Ex_Deriv()
    print('After raising the exception')
 
except Ex_Base as e:
    print('Ex_Base caught')  # this catches Ex_Deriv too
 
except Ex_Deriv as e:
    print('Ex_Deriv caught')  # never reached

Usage

# common exception handling pattern
try:
    result = risky_operation()
except SpecificError as e:
    handle_specific_error(e)
except GeneralError as e:
    handle_general_error(e)
finally:
    cleanup()

Important

Always order except blocks from most specific to most general exception types.


Appendix

Note created on 2024-09-18 and last modified on 2024-12-31.

See Also


(c) No Clocks, LLC | 2024