Before understanding handling an exception in python, let’s understand what exceptions are? In this tutorial, we’ll learn about exceptions in python, how to handle them, and a few examples.
An exception is an event that disrupts the normal flow of a program during execution. In layman terms, if python encounters an error in the code, it will stop it and will display an error message. The reason for an error can be a user error, network issue, or anything else.
Exceptions are categorized into two types, built-in exceptions and user-defined exceptions. Let’s understand an exception with an example.
a = 10 b = 2 print(a/b)
Here we know what the output will be. It will be
5. Now, what if we took user input for a and b and mistakenly, the user entered 0 for b. Let’s check this out.
a = 10 b = 0 print(a/b) print("End Code") # Output Traceback (most recent call last): File "main.py", line 4, in <module> print(a/b) ZeroDivisionError: division by zero
You know we cannot divide a number by 0 and python gives an error “ZeroDivisionError”. Imagine if our code had more statements to execute like in the above example but due to this error, the whole program ends right there.
To avoid such situations we use different blocks that are
Let’s solve the same example.
In python try-except block, try block will contain the critical operation which can raise an exception. If it encounters any error, it will directly jump to the except block.
a = 10 b = 0 try: print(a/b) except Exception: print("An error occurred") print("End Code")
An error occurred End Code
We put the same statement in a try block and if ti catches an error, it will move to the except block to execute that block. Now, we need to make sure that we either
except Exception which is a general term or the mention the
name of Exception to catch.
a = 10 b = 0 try: print(a/b) except ZeroDivisionError: print("You cannot divide a number by zero") print("End Code")
You cannot divide a number by zero End Code
Suppose you encounter an unknown error which is not syntax error and not a user error, what will you do in that case? You can use multiple except blocks in a code to avoid such situations.
a = 10 b = 0 try: print(a/b) except ZeroDivisionError: print("You cannot divide a number by zero") except Exception: print("Unknown Error occurred") print("End Code")
Using the Finally block in the code means this block will execute irrespective of the above output. This block is very useful when working with files and when we need to close the file after any operation.
try: f = open("example.txt", 'w') f.write("Test") print("Write operation was successful") except Exception: print("Something went wrong...") finally: f.close()
Write operation was successful
In the above example, we created a new file and performed a write operation. if the write operation was successful, it printed “Write operation was successful”. If it encountered an error, it would have printed “Something went wrong…”. But in the end,
finally block was executed to close the file.
Try…Except with Else
You can also use an
else statement with a try…except block. This block will run only when the try statement did not encounter any error.
num = 12 try: if num != 0: print("Non zero") except Exception: print("Something went wrong") else: print("No errors found")
Non zero No errors found