RuntimeError in Python: Causes and Fixes
RuntimeError is a general Python exception that happens while your program is running.
For beginners, this error can feel vague because the name does not tell you exactly what went wrong. The important clue is usually the message after RuntimeError and the traceback line that points to the problem.
This guide explains what RuntimeError means, why it happens, and how to debug it using simple real examples.
Quick fix
try:
# code that may fail at runtime
do_something()
except RuntimeError as e:
print('RuntimeError:', e)
Catching the error can help you inspect the message, but the real fix is to find the operation that fails during program execution.
If you are new to exceptions, see Python errors and exceptions explained and how to use try-except blocks in Python.
What RuntimeError means
A RuntimeError means a problem happened during execution, not before the program started.
Key points:
- It happens while the program is running
- Python or a library detected a runtime problem
- It is more general than errors like
ValueErrororTypeError - The message after
RuntimeErroris often the most useful clue
For example:
SyntaxErrormeans the code is written incorrectlyRuntimeErrormeans the code started running, but failed during execution
Why this error happens
RuntimeError often appears when the problem does not fit a more specific built-in exception.
Common reasons include:
- A library raises
RuntimeErrorfor a general runtime problem - Your code changes something while Python is still using it
- A generator or iterator stops in an unexpected way
- Recursion or environment state causes execution to fail
- A framework reports that something happened in the wrong state
In short, RuntimeError usually means:
"The program reached a bad state while running."
Simple example that raises RuntimeError
Programmers and libraries can raise this error directly.
raise RuntimeError("something went wrong")
Output:
Traceback (most recent call last):
File "example.py", line 1, in <module>
raise RuntimeError("something went wrong")
RuntimeError: something went wrong
The important part is the message:
something went wrong
In real programs, the message should be more specific.
For example:
user_logged_in = False
if not user_logged_in:
raise RuntimeError("Cannot load dashboard before login")
This is much more helpful because it tells you what state was invalid.
Common real-world cases
Dictionary changed size during iteration
A common runtime problem is changing a dictionary while looping through it.
data = {"a": 1, "b": 2, "c": 3}
for key in data:
if key == "b":
del data[key]
This raises:
RuntimeError: dictionary changed size during iteration
Why it happens:
- Python is iterating over the dictionary
- At the same time, the dictionary is being changed
- That makes the iteration unsafe
One fix is to loop over a copy of the keys:
data = {"a": 1, "b": 2, "c": 3}
for key in list(data.keys()):
if key == "b":
del data[key]
print(data)
Output:
{'a': 1, 'c': 3}
Generator raised StopIteration in the wrong place
Generators can also lead to runtime problems.
def broken_generator():
raise StopIteration("stop here")
yield 1
for item in broken_generator():
print(item)
In modern Python, this becomes a runtime error because raising StopIteration directly inside a generator is not the correct pattern.
A better approach is to use return to stop the generator:
def good_generator():
return
yield 1
for item in good_generator():
print(item)
This ends the generator cleanly.
Operation called in the wrong program state
Sometimes your own code should only run when something has already happened.
connected = False
def send_data():
if not connected:
raise RuntimeError("Cannot send data before connecting")
print("Data sent")
send_data()
This raises a RuntimeError because the program state is invalid.
Fix it by changing the state first:
connected = True
def send_data():
if not connected:
raise RuntimeError("Cannot send data before connecting")
print("Data sent")
send_data()
Output:
Data sent
Framework or package reports a runtime problem
Many third-party libraries use RuntimeError when something is technically wrong at runtime, but not a perfect match for another error type.
For example, a package may raise errors like:
RuntimeError: event loop is already runningRuntimeError: cannot schedule new futures after shutdownRuntimeError: model is not initialized
In these cases:
- Read the full message carefully
- Check the line in your code that called the library
- Look for setup steps that were missed or called in the wrong order
How to fix RuntimeError
When you see RuntimeError, do not focus only on the error name. Focus on the traceback and the message.
Use this process:
- Read the full traceback
- Look at the last line first
- Find the exact file and line number in your code
- Check what the program was doing at that line
- Inspect the values of nearby variables
- See whether you changed a collection during iteration
- Check whether the code ran in the wrong state
A few common fixes:
- Avoid changing a dictionary or set while looping over it
- Move state-changing code before or after the loop
- Make sure setup happens before dependent operations
- Replace direct
StopIterationin generators withreturn - Check whether a library expects a different calling order
If you need to recover from errors, see how to handle exceptions in Python.
Debugging checklist
Use this checklist when you are stuck:
- Read the last line of the traceback first
- Then read upward to find your file and line number
- Check variable values near the failing line
- Reduce the code to a small reproducible example
- Test one fix at a time
These commands and tools can help:
python your_script.py
python -m pdb your_script.py
Useful checks inside your code:
print(variable_name)
print(type(variable_name))
help(RuntimeError)
Example:
data = {"a": 1, "b": 2}
for key in data:
print("Current key:", key)
print("Dictionary before change:", data)
del data[key]
This kind of debug output helps you see exactly what happens before the crash.
If your problem involves deep repeated function calls, it may also be related to RecursionError in Python.
When to raise RuntimeError yourself
You can raise RuntimeError in your own code when the program reaches an invalid runtime state.
Example:
file_open = False
def write_report():
if not file_open:
raise RuntimeError("Cannot write report because the file is not open")
print("Report written")
This is reasonable when:
- The problem happens at runtime
- The state is invalid
- A more specific built-in exception does not fit better
Still, prefer a more specific exception when possible.
For example:
- Use
ValueErrorfor a bad value - Use
TypeErrorfor the wrong type - Use
RuntimeErrorfor a bad runtime state
If you are unsure about the difference between exception types, see TypeError vs ValueError in Python explained.
FAQ
Is RuntimeError the same as SyntaxError?
No. SyntaxError happens before the program runs. RuntimeError happens while the program is running.
How do I fix RuntimeError quickly?
Read the traceback, find the exact failing line, and use the error message to identify the invalid runtime condition.
Should I catch RuntimeError with try-except?
You can catch it for debugging or recovery, but you should still fix the real cause.
Can I raise RuntimeError myself?
Yes. You can use raise RuntimeError("message") when your program reaches an invalid runtime state.