To print an error in Python, you can 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 were like 10 and 0. Then we divide numbers 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. However, 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")
Output
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 in 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 errors.
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[0])
print("Array element at the index 1 is: ", arr[1])
print("Array element at the index 5 is: ", arr[5])
print("Array element at the index 6 is: ", arr[6])
except Exception as e:
print("The error raised is: ", e)
Output
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 the array displayed the output as the elements for indexes 0, 1, and 5. But for index 6, an error is raised, handled at the except block, and this error is list index out of range. So we printed this error message in except block.
Conclusion
In Python, you can use a try-except block to catch and handle exceptions. If an error occurs within the try block, it will be caught by the except block, where you can print out the error message.