RuntimeError in Python: Everything You Need to Know!

In this article, let us get ourselves up to speed on the RuntimeError exception in Python. In particular, we will try to answer the following questions.

  • What is RuntimeError exception?
  • When to expect a RunTimeError exception
  • What are the subclasses of RuntimeError?
  • How to fix RuntimeError?
  • When to raise a RuntimeError in our own code?

A good grasp of all the built-in exceptions in Python is crucial for anyone serious about becoming a Python Craftsman. This article is all about learning about Runtime Exceptions.

If you are not 100% familiar with the other built-in exceptions, I suggest reading the article linked below where we have handpicked the top 7 built-in exceptions that occur most frequently over a typical Pythoner’s career!
7 Most Common In-Built Exceptions in Python!

Alright, let’s start our discussion on RuntimeError by answering the following question!

What is RuntimeError exception?

Before understanding RuntimeError we must first understand the difference between Run-time and Compile-time

What is the difference between Run-time and Compile-time?

Usually, beginners confuse these 2 concepts, especially with Python as it is an interpreted language as opposed to languages like C and Java which are considered compiled languages.

While Python code is interpreted one line at a time, it is first compiled as a whole before the “line-by-line interpretation” starts. (source)

Hence even in Python, these are in fact different stages in the execution of the program.

Compile time in Python is the stage where your source code (i.e. your Python code) is converted to machine code (or executable code). In this stage, the syntax and semantics of the program are checked and a SyntaxError is raised if you violate any rules of the writing syntax.

For example, in the following code there is a SyntaxError and a ZeroDivisionError:

print(1/0

When you run the above code, only the SyntaxError will be triggered. There is no ZeroDivisionError because the interpreter hasn’t detected it yet because the code hasn’t been executed or run yet. Up to this point, the code is only checked for SyntaxError. Only when you have passed this stage, the code is run.

Runtime is simply the stage where the code is being executed. This is generally after compile time where it has been determined free of any syntax errors. Any errors other than the syntax error are raised here. A ZeroDivisionError for instance:

print(1/0)

When you run the above line, it will be checked for any syntactical mistakes and then it will be executed. The interpreter will then detect the division-by-zero mistake and will raise the appropriate error accordingly.

Is RuntimeError the same as “errors that occur during run-time”?

Yes and No!

To understand why, we must understand how the exceptions are categorized in Python.

The built-in Exceptions in Python can belong to one of several categories depending upon the nature of the problem.

If we try to categorize all the problems that can possibly occur during code execution, then we will end up with a million categories, most of which will never really occur.

So instead the makers of the Python programming language decided to group all the super-rare ones into a single category and named it RuntimeError exception.

The following excerpt is from the official Python docs

exception RuntimeError

Raised when an error is detected that doesn’t fall in any of the other categories. The associated value is a string indicating what precisely went wrong.

python.org

Hence to answer the question: What is a RuntimeError? we can say

RuntimeError is an exception in Python, which is raised if the nature of the error does not fall into any of the defined categories.

Hence to answer the question

Is RuntimeError the same as “errors that occur during run-time”?

Yes, RuntimeError is raised during run-time, but no, it’s not the only error that pops up during run-time!

I wish the developers of Python programming language named it MiscellaenousErrors instead to avoid confusion, but it is what it is! (and from my experience writing code for several years, giving names to classes is not an easy task, so I understand!)

Now that we have learned what RuntimeError is, next let’s go ahead and answer the following question.

What are the subclasses of RuntimeError? (NotImplementedError & RecursionError)

Even though RuntimeError is like a wild card to denote a number of miscellaneous errors that can happen during run-time, 2 of such errors proved to be more common than the rest, and hence they got special names. They are

  • NotImplementedError and
  • RecursionError

Lets have a brief look at these exceptions.

NotImplementedError

According to the Python documentation, the NotImplementedError is raised in 2 scenarios:

  1. When the abstract method lacks the required derived class to override the method
  2. The implementation of the method still needs to be done

RecursionError

The RecursionError is pretty simple, it’s an error when a recursive function is called one too many times.
You can check this out by running the following code which simply prints one number after another:

def my_recursive(num):
    print(num)
    my_recursive(num+1)

print(my_recursive(1))

Here’s another example:

def factorial(n):
    if n == 0:
        return 1
    else:
        return n * factorial(n-1)

result = factorial(5)
print(result)
120

That was a simple function that finds the factorial of a given number. But if you tried to find the factorial of a larger number, the RecursionError is triggered as the recursive function will be called too many times:

result = factorial(1000)
print(result)

Traceback (most recent call last):
  File "/home/main.py", line 7, in <module>
    result = factorial(1000)
  File "/home/main.py", line 5, in factorial
    return n * factorial(n-1)
  File "/home/main.py", line 5, in factorial
    return n * factorial(n-1)
  File "/home/main.py", line 5, in factorial
    return n * factorial(n-1)
  [Previous line repeated 995 more times]
  File "/home/main.py", line 2, in factorial
    if n == 0:
RecursionError: maximum recursion depth exceeded in comparison

How to fix RuntimeErrors?

Here is a pro tip for you, to fix not just RuntimeError but any error in Python. Whenever your program crashes with an Exception, don’t panic! Take a deep breath and have a look at the huge wall of error text that just got printed on your screen!

There is a wealth of information contained in the error message, if you wish to learn the tricks then set aside 10mins of your time and read the following article!

Python: Details contained in an Exception

For visual learners out there we have also made an interesting video on that topic!

Coming back to the question on how to fix RuntimeErrors, there is no silver bullet in this case as the error itself is a miscellaneous one! So just go through the process explained in the video above and that should get you home!

Let’s move on to the next question which is

When to raise RuntimeError?

If you are writing classes and you are in the process of error handling, it is generally recommended to raise specific error classes to be more informative to the user about the nature of the error. 

Here’s an example:

def divide(divident, divisor):
    if (divisor == 0):
        raise ZeroDivisionError("Oops! Your code ran into a ZeroDivisionError. You cannot divide a number by 0!")

In the above code, it was best to raise the ZeroDivisionError as it accurately described the situation instead of raising a RuntimeError like this

if (divisor == 0):
    raise RuntimeError("Oops! You code ran into an error!")

Always remember that RuntimeError represents a generic runtime problem without any specific categorization, unlike the other exception classes. It must be used when the specific cause of the error is not covered by any other exception class!

You can read more about available inbuilt exceptions in the exception section of our website

If none of the inbuilt exception suits your particular scenario, then I recommend making a custom exception class instead of using RuntimeError. You can read more about custom exceptions in the following article.

Custom Exception In Python: Everything You Need To Know!

Also it is worth noting that RuntimeError is not one of the most common exceptions you will run into in your daily life as a Python developer. Instead, you need to focus on 7 other errors mentioned in the article below if you wish to gain mastery in Python!

7 Most Common In-Built Exceptions in Python!

If you are a visual learner here is a YouTube video that we made on that same topic!

And on that note, I will end this article.

Congratulations on making it to the end of the article, not many have the perseverance to do so!

I hope you enjoyed reading this article and found it useful!

Feel free to share it with your friends and colleagues!

If your thirst for knowledge has not been quenched yet, here are some related articles that might spark your interest!

Related Articles

Exceptions in Python: Explained for Beginners!

ValueError: A Step By Step Troubleshooting Guide!

NameError: A Step By Step Troubleshooting Guide!

AttributeError: A Step By Step Troubleshooting Guide!

FileNotFoundError: A Step By Step Troubleshooting Guide!

Thanks to Namazi Jamal for his contributions in writing this article!

Photo of author
Editor
Balaji Gunasekaran
Balaji Gunasekaran is a Senior Software Engineer with a Master of Science degree in Mechatronics and a bachelor’s degree in Electrical and Electronics Engineering. He loves to write about tech and has written more than 300 articles. He has also published the book “Cracking the Embedded Software Engineering Interview”. You can follow him on LinkedIn