Industrial manufacturing
Industrial Internet of Things | Industrial materials | Equipment Maintenance and Repair | Industrial programming |
home  MfgRobots >> Industrial manufacturing >  >> Industrial programming >> Python

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:

  1. Syntax errors – problems detected during parsing.
  2. 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:

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:

ExceptionCause of Error
AssertionErrorRaised when an assert statement fails.
AttributeErrorRaised when an attribute assignment or reference fails.
EOFErrorRaised when the input() function hits an end‑of‑file condition.
FloatingPointErrorRaised when a floating‑point operation fails.
GeneratorExitRaised when a generator’s close() method is called.
ImportErrorRaised when the imported module cannot be found.
IndexErrorRaised when a sequence index is out of range.
KeyErrorRaised when a key is missing from a dictionary.
KeyboardInterruptRaised when the user presses Ctrl+C or Delete.
MemoryErrorRaised when an operation exceeds available memory.
NameErrorRaised when a variable is not found in local or global scope.
NotImplementedErrorRaised by abstract methods that lack an implementation.
OSErrorRaised for system‑related errors (e.g., file I/O).
OverflowErrorRaised when an arithmetic result is too large to represent.
ReferenceErrorRaised when a weak reference proxies a garbage‑collected object.
RuntimeErrorRaised for errors that don’t fit other categories.
StopIterationRaised by next() when an iterator is exhausted.
SyntaxErrorRaised when the parser encounters invalid syntax.
IndentationErrorRaised when indentation is incorrect.
TabErrorRaised when indentation mixes tabs and spaces inconsistently.
SystemErrorRaised when the interpreter detects an internal error.
SystemExitRaised by sys.exit().
TypeErrorRaised when an operation or function receives an object of an inappropriate type.
UnboundLocalErrorRaised when a local variable is referenced before assignment.
UnicodeErrorRaised for Unicode‑related encoding or decoding errors.
UnicodeEncodeErrorRaised during Unicode encoding errors.
UnicodeDecodeErrorRaised during Unicode decoding errors.
UnicodeTranslateErrorRaised during Unicode translation errors.
ValueErrorRaised when a function receives an argument of correct type but inappropriate value.
ZeroDivisionErrorRaised 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

  1. Python Keywords and Identifiers: Mastering Reserved Words and Naming Conventions
  2. Python Statements, Indentation, and Comments: A Clear Guide
  3. Python Namespaces & Variable Scope: Understanding Names, Bindings, and Scopes
  4. Mastering Python Loop Control: break & continue
  5. Mastering Directory and File Operations in Python
  6. Mastering Python Custom Exceptions: A Practical Guide
  7. Python vs JavaScript: Key Differences, Features, and When to Choose Each
  8. Python vs Ruby: A Comprehensive Comparison of Features, Advantages, and Use Cases
  9. Avoid Costly Mistakes: 7 Key Pick-and-Pack Errors and Proven Fixes
  10. Master Python Exception Handling: A Comprehensive Guide