To print an error in Python, use the try-except block. The try block is similar to the if statement, and the testing code is kept inside the try block. If the code raises an error, it is handled in an except statement. If the code does not raise any error, then this code is treated as a standard code. The code usually executes, and the except block is not executed.
a = 10 b = 0 c = a / b print(c)
In this code, we created two variables named a and b. Then, we assigned the values to a and be like 10 and 0. Then we divide the number a by b and store this quotient in the variable c.
If we execute the above program, it throws an error called the ZeroDivisionError. The ZeroDivisionError is raised because a number cannot be divided by zero in Python. If any number is divided by zero, then the output is infinity. Due to this, Python does not allow performing division by zero. We can catch this error by using try and except block.
a = 10 b = 0 try: c = a / b print(c) except ZeroDivisionError as e: print("You cannot divide a number by zero")
You cannot divide a number by zero
In this code, we used a try and except block for handling errors. Inside the try block, we calculated a / b and stored it to the variable c. Then, while dividing a by zero, the error is raised.
It raises an error called the ZeroDivisionError. Therefore, we have created an except block for the exception class as ZeroDivisionError. This exception class handles the error raised due to zero division error. Hence, the except block is executed, and the error message is printed.
Program for printing errors using general exception class
arr = [5, 6, 7, 8, 9, 10] try: print("Array element at the index 0 is: ", arr) print("Array element at the index 1 is: ", arr) print("Array element at the index 5 is: ", arr) print("Array element at the index 6 is: ", arr) except Exception as e: print("The error raised is: ", e)
Array element at the index 0 is: 5 Array element at the index 1 is: 6 Array element at the index 5 is: 10 The error raised is: list index out of range
In this program, we created an array called arr. We used a try block, and inside that try block, we printed the values at the indexes of 0, 1, 5, and 6. We can see the output as follows:
We can see that for indexes 0, 1, and 5, the output has been displayed as the elements present in the array. But for index 6, an error is raised, and that error is handled at the except block, and this error is list index out of range. So we printed this error message in except block.
That’s it for Print Error in try except in Python tutorial.
Krunal Lathiya is an Information Technology Engineer. By profession, he is a web developer with knowledge of multiple back-end platforms including Python. Krunal has written many programming blogs which showcases his vast knowledge in this field.