You finished your code. Everything looks great. The code is clean. The logic is clear. Let’s hit the run button. What can go wrong? oh right, Runtime Error!
Everybody who touched a code in his/her life encountered it. When the execution flow stops and raises an exception regarding something that went so wrong to the extent that your program cannot continue anymore.
In this post, we will see some common runtime errors with examples in Python.
Let’s go!
Index Out of Range
This usually happens when you are dealing with a list or array. The error means you are trying to access an array with an index that is out of range. But why?
When you allocate a list, the memory manager gives you specific memory slots that you can use. If you try to access something beyond these slots, it won’t let you:
my_list = [0] * 5
print(my_list[10])
Here our list has a length of five. As a result, accessing the index number 10 raises an exception in Python:
IndexError: list index out of range
Division by Zero
This is pure math. You cannot divide anything by zero. You cannot. Just accept it.
You think this is obvious. But when you have many variables in your script that change constantly, this can happen easily. Besides, you never know what the user put as input to your system. So always check!
num1 = 10
num1 -= 10
print(20 / num1)
Results in:
ZeroDivisionError: division by zero
Type Errors
Happens when you are doing an operation on some data type that is not supported.
It sometimes depends on your programming language. For instance, Javascript lets you use the “+” operator between an integer and a String. But in Python, no way:
name = 100
print("My name is: " + name)
Results in:
TypeError: can only concatenate str (not "int") to str
Value Errors
This happens when we give a function an input that is not possible to process by the function.
For example, there is a function named int() in Python that converts input to integer. But if the input is not convertible to an integer, it raises a Value Error:
int("2f")
Results in:
ValueError: invalid literal for int() with base 10: '2f'
Key Errors
The name is clear. When you try to access a key-value type of data structure, such as a dictionary in Python, but you provide a key that does not exist.
my_dict = {"1": 100}
print(my_dict["2"])
You will see:
KeyError: '2'
Attribute Errors
You encounter this when you try to access an object’s attribute that does not exist. Let’s say we have this class in Python:
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
Now I try to access the lastname of a person’s object:
p = Person("me", 30)
print(p.lastname)
whoops!
AttributeError: 'Person' object has no attribute 'lastname'
Assertion Errors
Assert is a great way to check our expected data values. Very useful when we are writing unit tests for instance. So this is the type of error that helps us to debug our code. Let’s say we have this function that has a bug:
def give_me_sum(a, b):
s = a + b
return a
Now, we try to test our function with assert in Python:
assert give_me_sum(2, 3) == 5
It is supposed to return 5 but it doesn’t since it has a bug. So we will see this instead:
----> 5 assert give_me_sum(2, 3) == 5 AssertionError:
Well, now we know that our function does not work!
Runtime errors always happen no matter how good you are in programming. They are not bad at all!
As a matter of fact, they are very useful for code debugging and controlling the flow. I try to write a post in the future about how can we benefit by intentionally raising runtime errors!
Hope you like this!
Link to the source code: https://github.com/Pooya-Oladazimi/blog-post-python/blob/master/runtime_error.ipynb
The End.