Common Built-in Exceptions Catalog
🏷️ Error Handling and Exceptions / What are Exceptions?
When Python encounters an error during program execution, it raises an exception. These exceptions are Python's way of telling you something went wrong. For engineers new to Python, understanding the most common built-in exceptions is essential for writing robust code and debugging effectively. Below is a catalog of the exceptions you'll encounter most frequently.
⚙️ What Are Built-in Exceptions?
- Python comes with a set of pre-defined exception classes, known as built-in exceptions.
- Each exception corresponds to a specific type of error (e.g., dividing by zero, accessing a missing file, using a wrong variable type).
- When an exception is raised and not handled, your program stops and displays a traceback showing the error type and location.
- Knowing these exceptions helps you:
- Debug faster by recognizing the error type immediately.
- Write better error handling by catching specific exceptions instead of using a generic catch-all.
📊 Common Built-in Exceptions Catalog
Below is a list of the most frequently encountered built-in exceptions, grouped by category.
🛠️ Input/Output and File Errors
- FileNotFoundError – Raised when trying to open a file that does not exist.
- Example: Attempting to read a file named config.txt that is missing from the current directory.
- PermissionError – Raised when you don't have the required access rights to a file or directory.
- Example: Trying to write to a system-protected file without administrator privileges.
- IOError – A general error for input/output operations (often a parent of FileNotFoundError and PermissionError).
- Example: A disk is full and you try to write data to a file.
🧮 Arithmetic and Value Errors
- ZeroDivisionError – Raised when dividing a number by zero.
- Example: Performing 10 / 0 in your code.
- ValueError – Raised when a function receives an argument with the correct type but an inappropriate value.
- Example: Calling int("abc") – the string cannot be converted to an integer.
- OverflowError – Raised when a calculation exceeds the limits of a numeric type (rare in modern Python for integers, but can occur with floats).
- Example: A floating-point operation that results in a number too large to represent.
🔍 Index and Key Lookup Errors
- IndexError – Raised when trying to access an index that is out of range for a list, tuple, or string.
- Example: Accessing my_list[10] when my_list only has 5 items.
- KeyError – Raised when trying to access a dictionary key that does not exist.
- Example: Using my_dict["missing_key"] when the key is not present.
- StopIteration – Raised to signal the end of an iterator (often seen in loops or generator functions).
🧬 Type and Attribute Errors
- TypeError – Raised when an operation or function is applied to an object of inappropriate type.
- Example: Adding a string and an integer together: "hello" + 5.
- AttributeError – Raised when trying to access an attribute or method that does not exist on an object.
- Example: Calling my_string.append("x") – strings do not have an append method.
- ImportError – Raised when an import statement fails to find a module or a name within a module.
- Example: Writing import nonexistent_module.
- ModuleNotFoundError – A subclass of ImportError, specifically for when the module itself is not found.
🔄 Control Flow and System Errors
- AssertionError – Raised when an assert statement fails.
- Example: assert 1 == 2 will raise this error.
- KeyboardInterrupt – Raised when the user presses Ctrl+C (or Delete) to interrupt program execution.
- Example: Stopping a long-running script manually.
- SystemExit – Raised by the sys.exit() function; if not caught, it causes the program to exit cleanly.
🕵️ Quick Reference Table
| Exception | When It Occurs | Common Example |
|---|---|---|
| FileNotFoundError | File does not exist | open("missing.txt") |
| ZeroDivisionError | Division by zero | 10 / 0 |
| ValueError | Invalid value for a type | int("hello") |
| IndexError | Index out of range | list[100] on a short list |
| KeyError | Missing dictionary key | dict["unknown"] |
| TypeError | Wrong type used | "text" + 5 |
| AttributeError | Attribute or method missing | "hello".append() |
| ImportError | Module not found | import fake_module |
| KeyboardInterrupt | User interrupts program | Pressing Ctrl+C |
💡 Tips for Working with Exceptions
- Read the traceback carefully – It tells you the exception type, the line number, and the specific operation that failed.
- Catch specific exceptions – Instead of using a bare except:, catch only the exceptions you expect (e.g., except FileNotFoundError:).
- Use the exception hierarchy – More specific exceptions (like FileNotFoundError) are subclasses of more general ones (like OSError). Catch the most specific one first.
- Don't over-catch – Silently catching all exceptions can hide bugs. At minimum, log the error or re-raise it after handling.
Understanding these common built-in exceptions will help you quickly diagnose issues and write more resilient Python code from the start.
This catalog documents the most common built-in exceptions in Python that engineers will encounter when their code encounters an error condition.
⚠️ Example 1: ZeroDivisionError — dividing by zero
This example shows what happens when you try to divide a number by zero.
numerator = 10
denominator = 0
result = numerator / denominator
📤 Output: ZeroDivisionError: division by zero
⚠️ Example 2: ValueError — passing an invalid argument to a function
This example shows what happens when you try to convert a non-numeric string to an integer.
user_input = "hello"
number = int(user_input)
📤 Output: ValueError: invalid literal for int() with base 10: 'hello'
⚠️ Example 3: TypeError — performing an operation on incompatible types
This example shows what happens when you try to concatenate a string and an integer.
name = "Engineer"
age = 30
message = name + " is " + age + " years old"
📤 Output: TypeError: can only concatenate str (not "int") to str
⚠️ Example 4: IndexError — accessing a list element that does not exist
This example shows what happens when you try to access an index beyond the length of a list.
scores = [85, 92, 78]
third_score = scores[3]
📤 Output: IndexError: list index out of range
⚠️ Example 5: KeyError — accessing a dictionary key that does not exist
This example shows what happens when you try to retrieve a value using a key that is not present in a dictionary.
user = {"name": "Alice", "age": 35}
city = user["city"]
📤 Output: KeyError: 'city'
⚠️ Example 6: FileNotFoundError — opening a file that does not exist
This example shows what happens when you try to read a file that is not present on the filesystem.
file_handle = open("missing_data.txt", "r")
content = file_handle.read()
file_handle.close()
📤 Output: FileNotFoundError: [Errno 2] No such file or directory: 'missing_data.txt'
⚠️ Example 7: AttributeError — calling a method that does not exist on an object
This example shows what happens when you try to use a method that is not defined for a given data type.
text = "hello"
text.reverse()
📤 Output: AttributeError: 'str' object has no attribute 'reverse'
⚠️ Example 8: ImportError — importing a module that is not installed
This example shows what happens when you try to import a module that Python cannot find.
import pandas_datareader
📤 Output: ModuleNotFoundError: No module named 'pandas_datareader'
Comparison Table
| Exception Name | When It Occurs | Common Cause |
|---|---|---|
| ZeroDivisionError | Dividing a number by zero | Denominator is zero |
| ValueError | Function receives an argument of correct type but wrong value | Invalid conversion (e.g., "abc" to int) |
| TypeError | Operation or function applied to object of inappropriate type | Mixing string and integer in concatenation |
| IndexError | Sequence subscript is out of range | Accessing list index beyond its length |
| KeyError | Dictionary key is not found | Using a key that does not exist in the dictionary |
| FileNotFoundError | File or directory does not exist | Opening a file that has not been created |
| AttributeError | Attribute reference or assignment fails | Calling a method that does not exist on the object |
| ImportError | Module cannot be imported | Module is not installed or name is misspelled |
When Python encounters an error during program execution, it raises an exception. These exceptions are Python's way of telling you something went wrong. For engineers new to Python, understanding the most common built-in exceptions is essential for writing robust code and debugging effectively. Below is a catalog of the exceptions you'll encounter most frequently.
⚙️ What Are Built-in Exceptions?
- Python comes with a set of pre-defined exception classes, known as built-in exceptions.
- Each exception corresponds to a specific type of error (e.g., dividing by zero, accessing a missing file, using a wrong variable type).
- When an exception is raised and not handled, your program stops and displays a traceback showing the error type and location.
- Knowing these exceptions helps you:
- Debug faster by recognizing the error type immediately.
- Write better error handling by catching specific exceptions instead of using a generic catch-all.
📊 Common Built-in Exceptions Catalog
Below is a list of the most frequently encountered built-in exceptions, grouped by category.
🛠️ Input/Output and File Errors
- FileNotFoundError – Raised when trying to open a file that does not exist.
- Example: Attempting to read a file named config.txt that is missing from the current directory.
- PermissionError – Raised when you don't have the required access rights to a file or directory.
- Example: Trying to write to a system-protected file without administrator privileges.
- IOError – A general error for input/output operations (often a parent of FileNotFoundError and PermissionError).
- Example: A disk is full and you try to write data to a file.
🧮 Arithmetic and Value Errors
- ZeroDivisionError – Raised when dividing a number by zero.
- Example: Performing 10 / 0 in your code.
- ValueError – Raised when a function receives an argument with the correct type but an inappropriate value.
- Example: Calling int("abc") – the string cannot be converted to an integer.
- OverflowError – Raised when a calculation exceeds the limits of a numeric type (rare in modern Python for integers, but can occur with floats).
- Example: A floating-point operation that results in a number too large to represent.
🔍 Index and Key Lookup Errors
- IndexError – Raised when trying to access an index that is out of range for a list, tuple, or string.
- Example: Accessing my_list[10] when my_list only has 5 items.
- KeyError – Raised when trying to access a dictionary key that does not exist.
- Example: Using my_dict["missing_key"] when the key is not present.
- StopIteration – Raised to signal the end of an iterator (often seen in loops or generator functions).
🧬 Type and Attribute Errors
- TypeError – Raised when an operation or function is applied to an object of inappropriate type.
- Example: Adding a string and an integer together: "hello" + 5.
- AttributeError – Raised when trying to access an attribute or method that does not exist on an object.
- Example: Calling my_string.append("x") – strings do not have an append method.
- ImportError – Raised when an import statement fails to find a module or a name within a module.
- Example: Writing import nonexistent_module.
- ModuleNotFoundError – A subclass of ImportError, specifically for when the module itself is not found.
🔄 Control Flow and System Errors
- AssertionError – Raised when an assert statement fails.
- Example: assert 1 == 2 will raise this error.
- KeyboardInterrupt – Raised when the user presses Ctrl+C (or Delete) to interrupt program execution.
- Example: Stopping a long-running script manually.
- SystemExit – Raised by the sys.exit() function; if not caught, it causes the program to exit cleanly.
🕵️ Quick Reference Table
| Exception | When It Occurs | Common Example |
|---|---|---|
| FileNotFoundError | File does not exist | open("missing.txt") |
| ZeroDivisionError | Division by zero | 10 / 0 |
| ValueError | Invalid value for a type | int("hello") |
| IndexError | Index out of range | list[100] on a short list |
| KeyError | Missing dictionary key | dict["unknown"] |
| TypeError | Wrong type used | "text" + 5 |
| AttributeError | Attribute or method missing | "hello".append() |
| ImportError | Module not found | import fake_module |
| KeyboardInterrupt | User interrupts program | Pressing Ctrl+C |
💡 Tips for Working with Exceptions
- Read the traceback carefully – It tells you the exception type, the line number, and the specific operation that failed.
- Catch specific exceptions – Instead of using a bare except:, catch only the exceptions you expect (e.g., except FileNotFoundError:).
- Use the exception hierarchy – More specific exceptions (like FileNotFoundError) are subclasses of more general ones (like OSError). Catch the most specific one first.
- Don't over-catch – Silently catching all exceptions can hide bugs. At minimum, log the error or re-raise it after handling.
Understanding these common built-in exceptions will help you quickly diagnose issues and write more resilient Python code from the start.
Interactive Views
You are currently in 📚 All-in-One mode. Use the tabs at the top to switch to 📖 Theory Only or 💻 Code Only views.
This catalog documents the most common built-in exceptions in Python that engineers will encounter when their code encounters an error condition.
⚠️ Example 1: ZeroDivisionError — dividing by zero
This example shows what happens when you try to divide a number by zero.
numerator = 10
denominator = 0
result = numerator / denominator
📤 Output: ZeroDivisionError: division by zero
⚠️ Example 2: ValueError — passing an invalid argument to a function
This example shows what happens when you try to convert a non-numeric string to an integer.
user_input = "hello"
number = int(user_input)
📤 Output: ValueError: invalid literal for int() with base 10: 'hello'
⚠️ Example 3: TypeError — performing an operation on incompatible types
This example shows what happens when you try to concatenate a string and an integer.
name = "Engineer"
age = 30
message = name + " is " + age + " years old"
📤 Output: TypeError: can only concatenate str (not "int") to str
⚠️ Example 4: IndexError — accessing a list element that does not exist
This example shows what happens when you try to access an index beyond the length of a list.
scores = [85, 92, 78]
third_score = scores[3]
📤 Output: IndexError: list index out of range
⚠️ Example 5: KeyError — accessing a dictionary key that does not exist
This example shows what happens when you try to retrieve a value using a key that is not present in a dictionary.
user = {"name": "Alice", "age": 35}
city = user["city"]
📤 Output: KeyError: 'city'
⚠️ Example 6: FileNotFoundError — opening a file that does not exist
This example shows what happens when you try to read a file that is not present on the filesystem.
file_handle = open("missing_data.txt", "r")
content = file_handle.read()
file_handle.close()
📤 Output: FileNotFoundError: [Errno 2] No such file or directory: 'missing_data.txt'
⚠️ Example 7: AttributeError — calling a method that does not exist on an object
This example shows what happens when you try to use a method that is not defined for a given data type.
text = "hello"
text.reverse()
📤 Output: AttributeError: 'str' object has no attribute 'reverse'
⚠️ Example 8: ImportError — importing a module that is not installed
This example shows what happens when you try to import a module that Python cannot find.
import pandas_datareader
📤 Output: ModuleNotFoundError: No module named 'pandas_datareader'
Comparison Table
| Exception Name | When It Occurs | Common Cause |
|---|---|---|
| ZeroDivisionError | Dividing a number by zero | Denominator is zero |
| ValueError | Function receives an argument of correct type but wrong value | Invalid conversion (e.g., "abc" to int) |
| TypeError | Operation or function applied to object of inappropriate type | Mixing string and integer in concatenation |
| IndexError | Sequence subscript is out of range | Accessing list index beyond its length |
| KeyError | Dictionary key is not found | Using a key that does not exist in the dictionary |
| FileNotFoundError | File or directory does not exist | Opening a file that has not been created |
| AttributeError | Attribute reference or assignment fails | Calling a method that does not exist on the object |
| ImportError | Module cannot be imported | Module is not installed or name is misspelled |