Mastering Python Errors & Built‑In Exceptions
Python Errors and Built‑In Exceptions
Discover how Python signals problems, the difference between syntax and runtime errors, and how to handle built‑in exceptions with confidence.
Video: Python Exception Handling
When you run a Python program, the interpreter stops execution immediately if it encounters an unhandled error. These errors fall into two broad categories:
- Syntax errors – problems detected during parsing.
- Logical errors (exceptions) – problems that arise while the code is executing.
Python Syntax Errors
A syntax error occurs when the source code violates Python’s grammatical rules. The interpreter points you to the exact location with a caret (^) in the error message.
> >>> if a < 3
File "<interactive input>", line 1
if a < 3
^
SyntaxError: invalid syntax
In this example the missing colon (:) after the if statement triggers a SyntaxError.
Python Logical Errors (Exceptions)
Logical errors, or exceptions, surface only after the code has passed the syntax check. Common examples include:
- Attempting to divide by zero (
ZeroDivisionError) - Opening a non‑existent file (
FileNotFoundError) - Importing an unavailable module (
ImportError)
When an exception is raised, Python creates an exception object. If it remains unhandled, a traceback is printed, showing the call stack and the reason for failure.
> >>> 1 / 0
Traceback (most recent call last):
File "<string>", line 301, in runcode
File "<interactive input>", line 1, in <module>
ZeroDivisionError: division by zero
> >>> open("imaginary.txt")
Traceback (most recent call last):
File "<string>", line 301, in runcode
File "<interactive input>", line 1, in <module>
FileNotFoundError: [Errno 2] No such file or directory: 'imaginary.txt'
Python Built‑In Exceptions
Python’s interpreter raises a wide range of built‑in exceptions to signal different failure conditions. You can list them with the following snippet:
print(dir(locals()['__builtins__']))
Below is a concise reference for some of the most frequently encountered built‑in exceptions and the situations that trigger them:
| Exception | Cause of Error |
|---|---|
AssertionError | Raised when an assert statement fails. |
AttributeError | Raised when an attribute assignment or reference fails. |
EOFError | Raised when the input() function hits an end‑of‑file condition. |
FloatingPointError | Raised when a floating‑point operation fails. |
GeneratorExit | Raised when a generator’s close() method is called. |
ImportError | Raised when the imported module cannot be found. |
IndexError | Raised when a sequence index is out of range. |
KeyError | Raised when a key is missing from a dictionary. |
KeyboardInterrupt | Raised when the user presses Ctrl+C or Delete. |
MemoryError | Raised when an operation exceeds available memory. |
NameError | Raised when a variable is not found in local or global scope. |
NotImplementedError | Raised by abstract methods that lack an implementation. |
OSError | Raised for system‑related errors (e.g., file I/O). |
OverflowError | Raised when an arithmetic result is too large to represent. |
ReferenceError | Raised when a weak reference proxies a garbage‑collected object. |
RuntimeError | Raised for errors that don’t fit other categories. |
StopIteration | Raised by next() when an iterator is exhausted. |
SyntaxError | Raised when the parser encounters invalid syntax. |
IndentationError | Raised when indentation is incorrect. |
TabError | Raised when indentation mixes tabs and spaces inconsistently. |
SystemError | Raised when the interpreter detects an internal error. |
SystemExit | Raised by sys.exit(). |
TypeError | Raised when an operation or function receives an object of an inappropriate type. |
UnboundLocalError | Raised when a local variable is referenced before assignment. |
UnicodeError | Raised for Unicode‑related encoding or decoding errors. |
UnicodeEncodeError | Raised during Unicode encoding errors. |
UnicodeDecodeError | Raised during Unicode decoding errors. |
UnicodeTranslateError | Raised during Unicode translation errors. |
ValueError | Raised when a function receives an argument of correct type but inappropriate value. |
ZeroDivisionError | Raised when dividing or taking the modulo by zero. |
If you need more granular control, Python allows you to define custom exception classes. See Python User‑defined Exceptions for details.
Handling exceptions is straightforward with try, except, and finally blocks. For a deeper dive, refer to Python try, except and finally statements.
Python
- Python Keywords and Identifiers: Mastering Reserved Words and Naming Conventions
- Python Statements, Indentation, and Comments: A Clear Guide
- Python Namespaces & Variable Scope: Understanding Names, Bindings, and Scopes
- Mastering Python Loop Control: break & continue
- Mastering Directory and File Operations in Python
- Mastering Python Custom Exceptions: A Practical Guide
- Python vs JavaScript: Key Differences, Features, and When to Choose Each
- Python vs Ruby: A Comprehensive Comparison of Features, Advantages, and Use Cases
- Avoid Costly Mistakes: 7 Key Pick-and-Pack Errors and Proven Fixes
- Master Python Exception Handling: A Comprehensive Guide