Python Try and Except Example
Today we will talk about one of the most important things in Python – exception handling. Firstly, let’s start with the definition of exceptions. They are errors detected while the program is being executed. So for example, if you write the program and you think it’s alright and try running it, it may give you some errors.
1. Basic exceptions
Let’s start with some basic exceptions.
Python Shell
>>> 1/0 Traceback (most recent call last): File "", line 1, in ZeroDivisionError: division by zero
So this program gives us the first error, because we can’t divide the number by zero. Let’s try another one.
Python Shell
>>> "string" + 5 Traceback (most recent call last): File "", line 1, in TypeError: must be str, not int
So we can’t concatenate the string with the integer number. When the program “crashes”, it means it finished execution with the result of error.
2. Exception handling
Now we are familiar with some of the errors that we may encounter while writing a program. Let’s try to handle those errors. We will create the basic program the takes two numbers and returns the result of its division.
Python
first = input() second = input() result = first/second print(result)
What happens when we execute the program? Try it for yourself! You will get a TypeError
. The reason is simple: when we use input()
method, we put the data in variables as string
, not as an integer
which we need. So how can we solve it? There are actually two ways to solve it: we may convert them to int
while asking a user for input, or we can convert them while dividing. I will show both ways.
Python
first = int(input()) second = int(input()) result = first/second print(result)
This one is preferrable if you know that you will be working with integers only. Another way is following:
Python
first = input() second = input() result = int(first)/int(second) print(result)
This one is preferrable if you know that the user may input some strings which you want to operate (but why would you need division in the first place then?). Anyway, I prefer the first method more.
So what happens if second
is zero? We get ZeroDivisionError: division by zero
error. Let’s handle it using try
and except
.
Python
first = input() second = input() try: result = int(first)/int(second) print(result) except Exception as e: print(e)
What we do here is that we actually print the type of error which occurs while executing. So if we try to divide by zero, we get division by zero
. We didn’t get any red lines, the program didn’t crash, so we handled the error successfully!
You may ask, “Hey, we only handle one error! What about the rest?”. I am glad that you asked (if you didn’t, don’t worry. I am glad that you are reading this article now anyway). So what happens if we enter strings, not integers? The program crashes, right? Let’ handle it.
Firstly, let’s think what we need to do. We ask a user for input and convert it to integer right away. Then, depending on the type of variables we do the following: if both are integer, we do calculate the division and handle DivisionByZero
exception as well, if at least one of the variables isn’t an integer, we show the user a warning message, and the program finishes. So what I want to do is to actually build a function that will do handling division error and division itself. Let’s call it division
. Then let’s call it only if both variables are integers.
Python
#division function def division(): try: result = first / second print(result) except Exception as e: print(e) #it's important to have division function before the code below try: first = int(input()) second = int(input()) division() except Exception as e: print("You can't put anything but integer numbers")
That’s about it. Let’s advance this program into one more step, shall we? What if we want to run the program until it actually gives us the result. What I mean is that right now the program stops while we put something but integer number. We want from a user to eventually put appropriate numbers, so the program will give us some result. The logic is quite similar (even though there are easier ways to do this, but this one seems pretty easy to follow). Let’s create the function calculation()
which will be the main one. We will still have the function division()
.
calculation.py
def division(first, second): try: result = first / second print(result) except Exception as e: print(e) def calculation(): try: first = int(input()) second = int(input()) division(first, second) except Exception as e: print("You can't put anything but integer numbers") calculation() calculation()
So now, try running it, and you will be able to get the result eventually.
3. Raising exceptions
Sometimes we would need to raise exceptions to debug our code. Usually, when you create your own exception, the best way is to create the class. Let’s do it:
raise.py
class Accident(Exception): def __init__(self, message): self.message = message def print_exception(self): print("Our custom exception is...", self.message) try: raise Accident("here") except Accident as a: a.print_exception()
So this is how we raise the exception: we create the class where we initialize the statement which will be printed, once the exception is raised. So our code raises an exception.
4. Finally statement
Finally statement is used to do the clean-up. For example, the code with finally
statement will run no matter what.
finally.py
dictionary = {"a":0, "b":1, "c":2} try: value = dictionary[input()] except KeyError: print("An error has occured!") else: print("Everything's fine") finally: print("It's finally over!")
So a user puts a Key
that will look for a matching key in the dictionary. If there is no match, it prints "An error has occured!"
. If there is a match, it prints "Everything's fine"
. It prints "It's finally over!"
no matter what.
5. Summary
So handling exceptions is a very important tool that is executed while debugging your program. You should definitely learn how to handle exceptions. Let’s sum up what we need to know:
try
is used to try to execute the code. If there are no errors, the program will finish successfully.except
is used for finding exceptions. You can handle multiple exceptions just writing anotherexcept
block of code. There are many built-in exceptions that you can find in the official documentation.raise
is used to raise your own exceptions. Once again, it’s not commonly used in production but can be quite handy in testing and debugging.finally
is used to test whether the program iterates correctly. For example, you may have a lot ofif-else
statments and you are not sure if it iterates the right block. You can putfinally
there to understand if the program runs correctly or not.
6. Homework
I hope error handling seems more logical for you now (if you were struggling with it). In fact, the best way to learn about errors and exceptions is to actually write code. It plays vital role in DRY principle (as known as Don’t Repeat Yourself).
So here is some homework for you:
Try to create a calculator in Python which will handle errors like putting strings, putting non-ASCII characters or very large numbers. Try to think about the time needed to calculate all inputs and make it as fast as possible. Try to avoid recursions (even though they look cool, they may slow your program down).
7. Download the Source Code
You can find all materials explained in this article below
You can download the full source code of this example here: try-catch.zip
Agree with Don’t Repeat Yourself importance. Pretty neat guide, though in practical life, handling exceptions requires more code reading. Moreover, let be fair, all of us use https://stackoverflow.com/ or https://fixexception.com/ to understand how to fix certain traceback, however true understanding comes only when you analyse traceback by yourself.
I mean what I can say – follow tracebacks, with debugger or by following github, not blindly copypaste recommendations