Python Built-in Exceptions
Python has a wide variety of built-in exceptions that are used to handle errors and other exceptional conditions. These exceptions can be raised by Python itself or manually triggered in your code using the raise statement. Here is a list of the most common built-in exceptions in Python, along with their descriptions and examples:
Common Built-in Exceptions
BaseException- The base class for all exceptions in Python. All other built-in exceptions are derived from this class.
- You usually don’t raise
BaseExceptiondirectly, but you catch it when you want to handle any exception.
try: pass except BaseException as e: print("An exception occurred:", e)Exception- The base class for most exceptions in Python. Almost all built-in exceptions derive from this class, except for system-exiting exceptions such as
SystemExit,KeyboardInterrupt, andGeneratorExit. - Typically used as a catch-all in exception handling.
try: pass except Exception as e: print("An exception occurred:", e)- The base class for most exceptions in Python. Almost all built-in exceptions derive from this class, except for system-exiting exceptions such as
ArithmeticError- The base class for errors related to arithmetic operations.
- Subclasses include
ZeroDivisionError,OverflowError, andFloatingPointError.
ZeroDivisionError- Raised when a division or modulo operation is attempted with zero as the divisor.
- Example:
try: x = 10 / 0 except ZeroDivisionError: print("Cannot divide by zero")OverflowError- Raised when the result of an arithmetic operation is too large to be expressed within the allowed range.
- Example:
import math try: print(math.exp(1000)) # This will raise an OverflowError except OverflowError: print("Number too large")FloatingPointError- Raised when a floating-point operation fails.
- Example:
# FloatingPointError is rarely raised, it often happens in hardware-dependent conditions.IndexError- Raised when trying to access an index that is out of range in a sequence (e.g., list, tuple).
- Example:
my_list = [1, 2, 3] try: print(my_list[5]) except IndexError: print("Index out of range")KeyError- Raised when trying to access a key in a dictionary that does not exist.
- Example:
my_dict = {"name": "Alice"} try: print(my_dict["age"]) except KeyError: print("Key not found")ValueError- Raised when a built-in operation or function receives an argument that has the right type but an inappropriate value.
- Example:
try: x = int("abc") # Trying to convert a non-numeric string to an integer except ValueError: print("Invalid value")TypeError- Raised when an operation or function is applied to an object of inappropriate type.
- Example:
try: x = "abc" + 5 # You cannot add a string and an integer except TypeError: print("Incompatible types")NameError- Raised when a local or global name is not found.
- Example:
try: print(unknown_variable) except NameError: print("Variable not defined")AttributeError- Raised when an attribute reference or assignment fails.
- Example:
class MyClass: pass my_obj = MyClass() try: my_obj.some_attribute except AttributeError: print("Attribute not found")ImportError- Raised when an import statement fails to import a module or a specific name from a module.
- Example:
try: import non_existent_module except ImportError: print("Module not found")ModuleNotFoundError- A subclass of
ImportError, raised when a module could not be found. - Example:
try: import non_existent_module except ModuleNotFoundError: print("Module not found")- A subclass of
StopIteration- Raised by the
next()function to indicate that there are no further items in an iterator. - Example:
my_list = [1, 2, 3] iterator = iter(my_list) try: while True: print(next(iterator)) except StopIteration: print("End of iterator")- Raised by the
StopAsyncIteration- Raised when an asynchronous iterator’s
__anext__method signals that there are no more items. - Example:
async def my_async_gen(): yield 1 yield 2 async_gen = my_async_gen() try: await async_gen.__anext__() except StopAsyncIteration: print("End of async iterator")- Raised when an asynchronous iterator’s
IOError- Raised when an I/O operation (e.g., file reading/writing) fails. In Python 3, it’s an alias of
OSError. - Example:
try: with open("non_existent_file.txt", "r") as file: pass except IOError: print("I/O error occurred")- Raised when an I/O operation (e.g., file reading/writing) fails. In Python 3, it’s an alias of
OSError- Raised when a system-related error occurs (e.g., file not found, disk full).
- Example:
try: with open("non_existent_file.txt", "r") as file: pass except OSError: print("OS error occurred")FileNotFoundError- Raised when trying to open a file that does not exist. It’s a subclass of
OSError. - Example:
try: open("non_existent_file.txt", "r") except FileNotFoundError: print("File not found")- Raised when trying to open a file that does not exist. It’s a subclass of
EOFError- Raised when the
input()function hits an end-of-file condition (EOF) without reading any data. - Example:
try: input("Enter something: ") except EOFError: print("End of file reached")- Raised when the
RuntimeError- Raised when an error occurs that does not fall under any other specific category.
- Example:
def recursive(): return recursive() try: recursive() except RuntimeError: print("Runtime error occurred")RecursionError- A subclass of
RuntimeError, raised when the maximum recursion depth is exceeded. - Example:
try: def recursive(): return recursive() recursive() except RecursionError: print("Recursion depth exceeded")- A subclass of
SyntaxError- Raised when there is an error in Python syntax.
- Example:
try: eval("x === x") except SyntaxError: print("Syntax error")IndentationError- Raised when the indentation is incorrect (e.g., unexpected indentation or inconsistent indentation).
- Example:
# Inconsistent indentation would cause an IndentationError.KeyboardInterrupt- Raised when the user interrupts program execution, usually by pressing
Ctrl+C. - Example:
try: while True: pass except KeyboardInterrupt: print("Execution interrupted by user")- Raised when the user interrupts program execution, usually by pressing
SystemExit- Raised when the
sys.exit()function is called, signaling that the program should terminate. - Example:
import sys try: sys.exit() except SystemExit: print("SystemExit called")- Raised when the
Summary:
- General:
BaseException,Exception,RuntimeError,RecursionError,SystemExit,KeyboardInterrupt - Arithmetic:
ArithmeticError,ZeroDivisionError,OverflowError,FloatingPointError - Lookup:
IndexError,KeyError - Value/Type:
ValueError,TypeError,AttributeError,NameError - I/O:
IOError,OSError,FileNotFoundError,EOFError - Iteration:
StopIteration,StopAsyncIteration - Importing:
ImportError,ModuleNotFoundError - Syntax:
SyntaxError,IndentationError
These built-in exceptions are essential for handling various types of errors and ensuring your Python programs run smoothly under all conditions.