🐍 Python Beginner

What is exception handling in Python?

Answer

Python uses try-except-else-finally blocks for exception handling. try contains code that might raise an exception. except ExceptionType as e catches a specific exception. Multiple except clauses handle different exception types. except (TypeError, ValueError) as e catches multiple types. Bare except catches all exceptions (avoid this). else block runs only if no exception occurred. finally always runs (used for cleanup — closing files, releasing locks). Raise exceptions with raise ValueError("Invalid input"). Re-raise with raise (no arguments). Python's exception hierarchy starts at BaseExceptionException → specific classes. Common exceptions: ValueError, TypeError, KeyError, IndexError, AttributeError, FileNotFoundError, ZeroDivisionError.