RuntimeError

RuntimeError is a built-in exception that Python raises when an error has occurred that doesn’t fall into any other error category. It’s a generic exception often raised when a more appropriate exception isn’t available.

RuntimeError Occurs When

A RuntimeError typically appears when Python encounters an unexpected situation that doesn’t match a more specialized built-in exception.

RuntimeError Can Be Used When

  • Handling unexpected errors that don’t have a specific exception
  • Catching errors in external libraries or modules that might not have detailed exception handling
  • Debugging complex code where the exact nature of the error isn’t immediately clear

You should use RuntimeError sparingly.

RuntimeError Examples

An example of when the exception appears:

Python
>>> numbers = {1, 2, 3}
>>> for item in numbers:
...     numbers.remove(item)
...
Traceback (most recent call last):
    ...
RuntimeError: Set changed size during iteration

An example of how to handle the exception:

Python
>>> numbers = {1, 2, 3}
>>> try:
...     for item in numbers:
...         numbers.remove(item)
... except RuntimeError as e:
...     print(f"Caught a RuntimeError: {e}")
...
Caught a RuntimeError: Set changed size during iteration

Tutorial

Python's Built-in Exceptions: A Walkthrough With Examples

In this tutorial, you'll get to know some of the most commonly used built-in exceptions in Python. You'll learn when these exceptions can appear in your code and how to handle them. Finally, you'll learn how to raise some of these exceptions in your code.

intermediate python

For additional information on related topics, take a look at the following resources:


By Leodanis Pozo Ramos • Updated March 26, 2025 • Reviewed by Martin Breuss