Built-in Exceptions
Python has a rich hierarchy of built-in exceptions that cover the most common error conditions you will encounter. Knowing these exceptions by name and und...
Python Built-in Exceptions: What They Are and When They Occur
Python has a rich hierarchy of built-in exceptions that cover the most common error conditions you will encounter. Knowing these exceptions by name and understanding when they occur is essential for writing robust programs and for debugging when things go wrong.
All built-in exceptions inherit from BaseException at the top of the hierarchy. The most commonly used subclass is Exception, which is the base class for most errors that programs should catch and handle. Below Exception, Python organizes exceptions into logical groups.
ValueError is raised when a function receives an argument of the right type but an inappropriate value. Calling int("hello") raises a ValueError because the string cannot be converted. TypeError occurs when an operation is applied to an object of an unsuitable type, such as adding a string to an integer.
KeyError occurs when you try to access a dictionary key that does not exist. IndexError is similar but happens when you use an index that is out of range on a list. AttributeError is raised when you access an attribute that an object does not have, and NameError occurs when a variable name is not found in the current scope.
try: numbers = [1, 2, 3] print(numbers[10]) except IndexError as e: print(f"Caught an error: {e}")
ZeroDivisionError is raised when you divide a number by zero. FileNotFoundError occurs when you try to open a file that does not exist. ImportError is raised when an import statement fails to find the module.
RuntimeError is a catch-all for errors that do not fit neatly into other categories. OverflowError occurs when the result of an arithmetic operation is too large. MemoryError is raised when an operation cannot allocate enough memory.
Understanding the exception hierarchy is important because when you catch an exception, you also catch all of its subclasses. Catching Exception catches almost everything except system-exit-level events. Catching BaseException also catches SystemExit and KeyboardInterrupt, which is rarely what you want.
Exam tip: Python's exception class hierarchy is a favorite exam topic. Know that BaseException is the top-level class, Exception sits below it, and common exceptions like ValueError, TypeError, and KeyError all inherit from Exception. Catching a parent class catches all its children.