Image of Python RuntimeError (Examples & Use Cases) | Initial Commit

ADVERTISEMENT

Table of Contents

Introduction

There are several types of errors in Python that help you debug your code. When you run your code, Python first checks for any syntax errors, and then runs the code. Errors that are thrown once the code is run are called runtime errors. In this tutorial, you will learn several different types of runtime errors and how to fix them.

What is a Runtimeerror in Python?

A runtime error is a type of built-in python exception that is thrown at runtime. There are many different types of runtime errors, we will cover them in this article. Some examples include type errors and name errors. Runtime errors fall under a larger group of concrete exceptions in Python.

What causes run time error in Python?

There are many things that can cause a runtime error depending on the type of error that is thrown. Some common causes of runtime errors include:

  • dividing by zero
  • using incorrect types in operations
  • indexing past the length of a list
  • accessing a key in dictionary that doesn't exist
  • using variables that haven't been defined yet
  • trying to access a file that does not exist.

How do you handle a runtime error in Python?

How you handle a runtime error depends on the specific error that was thrown. Once way to generally handle runtime errors is by using a try/except block. You can specify how you want to handle the code in the case of an error in the except block, here is an example:

>>> y = 12
>>> x = 0
>>> try:
... z = y / x
>>> except:
...print("An error occurred")
...z = 0

This way you are alerted of the error without an exception being thrown and stopping your code.

What is runtime error example?

Let's take a look at some examples of common runtime errors and how to fix them.

Zero Division Error raised

A ZeroDivisionError is thrown when you try to divide or modulo by zero in your code, for example:

>>> x = 0
>>> y = 2
>>> if y % x == 0:
... print(y, :is divisible by", x)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ZeroDivisionError: integer division or modulo by zero

We can avoid this by adding a check to make sure the number we're modding by isn't 0 before we perform the operation:

>>> x = 0
>>> y = 2
>>> if (x != 0) and (y % x == 0):
... print(y, "is divisible by", x)

Type Error

A TypeError is thrown when you try to perform an operation with incorrect types. For example, if you tried to concatenate an int and a string, you get a type error:

>>> x = "1"
>>> y = 2
>>> z = x + y
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for +: 'int' and 'str'

The error will also specify which operation is throwing the error and what types you're trying to use. In this case we can resolve this error by casting all the variables to integers to make sure we are only adding integers:

>>> x = "1"
>>> y = 2
>>> z = int(x) + int(y)
>>> print(x+y)
3

Another common cause for type errors is attempting to loop through an incorrect type. For example, attempting to iterate through an integer:

>>> for i in 10:
... print(i)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'int' object is not iterable

In this case the error tells us that we are attempting to iterate through an integer, which is not a type we can iterate through. Instead we want to use a for-range loop:

>>> for i in range(10):
... print(i)
0
1

Key Error

A KeyError is thrown when you are trying to access a key in a dictionary that doesn't exist. For example:

>>> d = {1: ["a"], 2: ["b"]}
>>> print(d[3])
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
KeyError: 3

The error will specify which key you are trying to access that does not exist. You can fix this by making sure to check if the key is in the dictionary before trying to access that specific key. You can check if a key exists in a dictionary by using the in function, which returns a boolean:

>>> d = {1: ["a"], 2: ["b"]}
>>> if 3 in d:
... print(d[3])

Index Error

An index error is caused by indexing into a list with an out of bounds index:

>>> L = [1,2,3]
>>> for i in range(10):
... print(L[i])

We can fix this by either adjusting the for loop to only loop over the range of the list, or adding a check before we index into the list to make sure the index is in range:

>>> L = [1,2,3]
>>> for i in range(len(L)):
... print(L[i])

or

>>> L = [1,2,3]
>>> for i in range(10):
... if i < len(L):
... print(L[i])

Name Error

A NameError is thrown when you try to use a variable that is not defined yet in the file. For example:

>>>print(x)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'x' is not defined

You can fix this by defining the variable before it is used in the file:

>>>x = 5
>>>print(x)
5

A name error can also be thrown if you try to use a variable that is already defined but out of scope. For example, if you try to use a local variable defined inside of a function globally:

>>>def foo(x,y):
             print(x + y)
>>>
>>>print(x)
Traceback (most recent call last):
  File "<string>", line 4, in <module>
NameError: name 'x' is not defined

To fix this, make sure you are only trying to access variables that are within scope.

File not found error

A FileNotFoundError is thrown when you try to access a file that does not exist in the directory you specified:

>>> open("file", "r")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
FileNotFoundError: [Errno 2] No such file or directory: 'file'

There are a couple ways to resolve the error. First you should check to make sure that the file you are trying to access is in your current directory. If not, make sure to specify the full filepath when trying to access that file, for example:

>>> open("/C:/folder1/folder2/file", "r")

How do I fix a value error in Python?

A value error is caused by giving a function an argument that is of the correct type, but an incorrect value. For example:

>>>import math
>>>math.sqrt(-100)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: math domain error

Here we get an error because the math.sqrt function only works with positive integers or zero. We can prevent this error by making sure that anything passed into the function is greater than or equal to zero.

What causes an overflow error?

An overflow error is caused by an arithmetic operation that is too large for Python to represent.

For example:

>>>math.exp(5000)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
OverflowError: math range error

You can prevent overflow errors by making sure that the numbers you pass into functions are not too large.

Summary

In this tutorial, you learned that runtime errors are, when they occur, and many ways to fix them. First, you learned that runtime errors are a type of exception thrown at runtime. Next, you learned some common causes of runtime errors like dividing by zero and using incorrect types in operations. Then, you learned how to generally handle runtime errors using a try-except block. Finally, you looked at several examples of things that can cause runtime errors and how to resolve them, including some less common errors like overflow errors and value errors.

Next steps

If you're interested in learning more about the basics of Python, coding, and software development, check out our Coding Essentials Guidebook for Developers, where we cover the essential languages, concepts, and tools that you'll need to become a professional developer.

Thanks and happy coding! We hope you enjoyed this article. If you have any questions or comments, feel free to reach out to jacob@initialcommit.io.

References

  1. Concrete Exceptions
  2. Built-in Exceptions

Final Notes