This is a detailed tutorial of Try and Except in Python. Test your code and handle errors with try and except block. The finally block is also explained.
Try, Except & Finally
In almost every other programming language, try, catch and finally, blocks are available for the purpose of handling errors and exceptions during the runtime of a program.
Try Block is just to test run a piece of code written in this block. If it works perfectly without any errors, the code written in the except block will not be executed. If any error occurred while running the code written in the try block, the error has to catch by the except block. If the error so raised by the code of the try block will match with the except block, the code of the except block will be executed.
There’s one more block associated with try and except and it is finally. The code written in this block will execute regardless of the fact that whether the code in the try block raises an error or not. It will run for sure.
Therefore, Try block will test your code, except will handle its errors and finally will execute for sure. This concept is also known as Exception Handling.
The syntax is simple, each block has to defined with the keywords try, except and finally respectively. The same order of the blocks has to be followed. The use of finally block is an option but try and catch blocks are always used together.
try: #Write the Test Code Here except: #Code To Handle the Error Raised finally: #Code that has to be executed regardless of any error
There are different types of exceptions that can be raised by the code and detected by the try block. Therefore, you can add , multiple except blocks that can handle different types of exceptions raised. The following syntax defines a program that handles three different types of exceptions.
try: #Write the Test Code Here except exception_1: #Code To Handle the exception_1 except exception_2: #Code To Handle the exception_2 except exception_3: #Code To Handle the exception_3 finally: #Code that has to be executed regardless of any error
It is the concept of handling coding exceptions that usually occur during the runtime of a computer program. Let’s say you are letting the end-user give some input to the program and according to that input, your program processes some output. Now, what if the end-user inputs a wrong or invalid value?
Your code will not work and will raise errors. A good programmer makes its program so robust that it can handle almost all of the known and possible runtime errors. For the purpose of making your python or any other language program so robust that it can handle such errors, we make use of the concept of Exception Handling. In python, we make use of try and except block for Exception Handling.
Python offers some inbuilt exceptions that the try block can detect. The following mentioned are types of these common exceptions.
- IOError. To raise an exception while an input-output error occurs.
- KeyboardInterrupt. To raise an exception on wrong keyword input.
- ValueError. To raise an exception on the wrong value encountered.
- EOFError. While reading files, the end is reached, this exception is raised.
- ImportError. When a python module used in the try code does not found, this exception is raised.
There are many more exceptions that can be handled depending on the different modules that you’re using in your python program.
Let’s begin with the simplest example. Consider the following code snippet.
try: print(age) except: print("Error: An Exception is Raised!")
As you can see in the output of the above code, instead of running the code in the try block, it raises the exception and executes the print statement written in the except block.
The error is raised because the variable
age is not defined. In this code, there was a single line of code written in the try block, so we’re able to find the exception easily, but what if the program is lengthy?
Finding The Exception
The except block can also tell you the name of the exception raised. Observe the following code and its output.
try: print(age) except Exception as ExceptionName: print(ExceptionName)
You can see that now the output says the exact exception raised. This way you can identify the right cause of exception so raised in a try-except block. Once you know the exact name of the exception, you can further handle it better using if-else and other conditions.
Catch Custom Exceptions
You can also catch different types of exceptions in different except blocks as already mentioned in the Syntax section. But for that must first know the name of the exception to be handled.
Let’s understand this with the help of an example.
ZeroDivisionError is one of the most common exceptions. The following program is written to handle this exception.
try: num1 = 10 num2 = 0 result = num1/num2 print(result) except ZeroDivisionError: print("Denominator can not be Zero.")
num2 is 0 and dividing with 0 is not possible, so we’re catching a custom error named
ZeroDivisionError in python. Like this, there many different kinds of exceptions that can be caught. You can find the complete list of Python built-in exceptions here.
This way, you can also add multiple except blocks with different exceptions and can also add the default except block at the end without adding any exception name to handle any rest of the unknown exceptions. An example illustrating the same is written below.
try: print("Enter 1st Number") #num1 = int(input()) print("Enter 2nd Number") num2 = int(input()) result = num1/num2 print(result) except ZeroDivisionError: print("Denominator can not be Zero.") except NameError: print("Some Variable is Not Defined") except Exception as ExcpetionName: print("Error. An Exception Occured. Details: " + ExcpetionName)
You can in the output as the variable
num1 is not defined so the NameError exception is raised and the print statement in the corresponding except block runs. But this program is also capable of handling the
ZeroDivisionError and any other exception as well.
Raise an Exception
The try block raise an exception automatically. But we can also raise an exception manually with the help of the keyword
raise. Till now we’ve used the inbuilt-exceptions in the examples but this way you can create your own exceptions and can also raise them yourself.
For example, we’ve written a program that tells the square root of a number only if the user enters a positive numerical value, otherwise, it raises an exception that the number should be positive.
import math try: print("Enter The Number:") num = int(input()) if(num>0): squareRoot = math.sqrt(num) print(squareRoot) else: raise Exception("NegativeNumberError") except Exception as ExceptionName: print("Error: " + str(ExceptionName))
You can see as we entered the Negative Number, it raises the NegativeNumberError, which we’ve raised manually in the try block code. This way, you can raise as many custom exceptions as you want using the keyword
The finally block always executes regardless of the fact that the error occurs or not. This can be used for different purposes such as to tell the user that the program has stopped its execution. We’ve given the same example as given in the above section with the addition of finally block to tell the user that the program has completed its execution in both the cases when the error of Negative Number occurs and when the Square root is calculated successfully.
import math try: print("Enter The Number:") num = int(input()) if(num>0): squareRoot = math.sqrt(num) print(squareRoot) else: raise Exception("NegativeNumberError") except Exception as ExceptionName: print("Error: " + str(ExceptionName)) finally: print("The Program has completed its execution.")
Case 1: When No Exception Raised
The following screenshot shows when the given number is positive and no exception is raised, the
finally block is executed successfully, running the only print statement written inside it.
Case 2: When the Exception is Raised
The following screenshot shows the execution of the
finally block, when the NegativeNumberError is encountered.
So, this way you can easily handle errors in python with Try and Except. I hope you found this guide useful. If so, do share it with others who are willing to learn Python. If you have any questions related to this article, feel free to ask us in the comments section.