I’m sure everyone who has programmed before has encountered errors in their code. Mostly you would have found yourself in a situation where your program was not executing as expected because your code needed correction. But imagine a scenario when you are unsure whether you will encounter an error as your program depends on an external factor. In this case, it depends on the input for your program, whether you will encounter an error or not. With Python, this is when you would use the powerful try-except.
An example of this would be when you are connecting to an external API or library. The connection will likely be successful, but sometimes it won’t be. But that might not be a fault in your code and instead a problem with the external resource. If your program does not properly connect, then it’s going to affect the rest of your code which depends on a successful connection and it might end up crashing your program.
Another example is when you want to divide a given number by another number the user inputs. If the user inputs a non-zero number, the program will run successfully. However, if the user enters 0, then your program will end up crashing. In this article, we will use this as an example to see how we can use the try-except to catch exceptions.
What are Errors and Exceptions
Before we start looking at the try-except blocks, we need to get familiar with errors and exceptions.
Simply put, errors are problems in the code that cause the program to crash. There are two main types of errors. Syntax errors and Runtime errors.
- Syntax errors are due to problems in the format of your code. Python has some rules as to how you have to write your code. If you don’t follow them however, python will not be able to execute your code as its not written in an understandable way. Also note that for other programming languages the syntax will be different. For example, in python you do not need semi colons after each line. In java however, you need to.
- The other error, which occurs during runtime, is the runtime error. Any error found during runtime is an exception. There are many types of runtime errors which are all found as your program is running. Runtime errors are a result of the execution of the code rather than the syntax. There is no guarantee that you will not encounter an error, even if you adher to the proper syntax. Some common runtime errors you might encounter are…
- EOFError – When the file reader hits the end of the file without reading anything
- IOError – When a file can’t be opened
- IndexError – When trying to find an element beyond the sequence’s length
- NameError – When the variable has not been initialized and is unknown in the local or global scope
- TypeError – When a parameter of the wrong type has been given in a function
- ZeroDivisionError – When trying to divide by 0
Integrating the Try-Except Blocks Into your Code
Below is the outline for the try-except code. Only the try and except block is necessary although adding the else and finally block gives more functionality. Let’s take a look at what each block does and how python will maneuver through this.
try: # The try block code except: # The except block code else: # The else block code finally: # The finally block code
Introducing the Example
As we walk through how to use a try-except, let’s use the example of trying to divide two numbers and how we can handle the possible ZeroDivisionError. First, let’s write that without any try-except and use two numbers which we know won’t result in the error.
a = 4 b = 2 c = a / b print(c)
When running the above code, we see the number 2 because 4 divided by 2 is 2. But what if we change b to equal 0 instead? Without any error handling, the program will crash and we will see the ZeroDivisionError.
Using the Powerful Try-Except Blocks
When we use the try-except, if an error occurs within the try block, we will be able to catch it. This means that the program will not crash and instead execute the code inside the except block. So we should move the code that would possibly result in an error to within the try block. To the except block we add code which, In case the error occurs will execute. Here is an example of what we can change our basic code to.
a = 4 b = 0 try: c = a / b print(c) except: print("There was an error")
There was an error
Now when we run this code, we will see the printed message, “There was an error”. Since the code inside the try block resulted in a error, the except block caught it and executed that code instead.
Another way to write this would be to specify what error to catch with the except statement. This only catches that specific error, so be careful to make sure that that is the only error that could occur. You could also include another except statment below to catch another error. So you could rewrite the code like this.
a = 4 b = 0 try: c = a / b print(c) except ZeroDivisionError: print("There was a division by zero error") except: print("There was an error")
There was a division by zero error
In this example, if the error that is caught in the try block is the ZeroDivisionError, the first except will execute. If not, then the second except will execute instead.
Usually you would use a try-except when you don’t know the outcome. For our example, we know what will execute because we know the input numbers and know if the error will occur. Say you ask the user to give two numbers instead, then it might work or might not. That would be a better time to use the try-except blocks, but for example purposes, I will continue to use pre-determined numbers.
Adding the Other Powerful Blocks: Else and Finally
If no error is found, the else block will execute. In this example, we can move the print(c) to the else block. This is because we execute that line only if there is no error.
a = 4 b = 2 try: c = a / b except ZeroDivisionError: print("There was a division by zero error") except: print("There was an error") else: print(c)
In this case, when we run the program, our code tries to divide 4 by 2. Because it does not result in a ZeroDivisionError it runs the else block after the try block and we see the quotient being printed, which is 2.
Finally, The finally block executes all the time regardless of the try-except result. So if there was an error or even if there wasn’t one caught, the finally block would execute. So we could add a general statment here. For this example there is no real need for the finally block but we can add it just to see the flow of the program. This is the final version of our code.
a = 4 b = 2 try: c = a / b except ZeroDivisionError: print("There was a division by zero error") except: print("There was an error") else: print(c) finally: print("The code is finished")
2 The code is finished
These are all the blocks available to use the try-except. The try and except block are mandatory, but the other two are optional and you might need to use them depending on the situation. The try-except is a very useful tool when you expect some error to occur that is not in your hands and is a great way to handle it and keep the code running.
Hope you try to use this in your code to catch some exceptions.