Python RuntimeError Exception
Example
A RuntimeError occurs if you add items to a dictionary while you loop through it:
fruits = {"apple": 1, "banana": 2}
for key in fruits:
fruits["cherry"] = 3
Try it Yourself »
Definition and Usage
The RuntimeError exception occurs when an error does not belong to any of the other exception types.
In the example, the dictionary gets a new item while the loop goes through it, which is not allowed.
Tip: Loop through a copy of the keys instead: for key in list(fruits):.
Exception Handling
Example
Handling the RuntimeError in a try...except statement:
fruits = {"apple": 1, "banana": 2}
try:
for key in fruits:
fruits["cherry"] = 3
except RuntimeError:
print("Do not change a dictionary while you loop through it")
Try it Yourself »
Related Pages
Read more about handling errors in our Python Try Except Tutorial.