The programming languages are designed in such a way that they have their methods and built-in functions to deal with the error. The same case is for Python. Python efficiently utilizes its built-in methods to handle the error and print the exceptions when the input is entered in a wrong manner. Python contains certain methods to deal with the exceptions in the code.
In this article, first, we will discuss what is meant by an exception in Python and different methods to print an exception in Python.
Exception in Python
The exception in Python is defined as the error that occurs when the code is executed and it further blocks the execution of code after the occurrence of an error. The exception works in such a manner that an object is created for the error which contains the type of error that occurred during execution.
How to Print Exception in Python?
To print an exception in Python three different methods are try-except block, traceback, and logging.exception. When any of these methods are implemented the next involves the print() function to print the exception on the screen. One of the most common and simple ways to print the exception is by implementing the try-except block.
Below is the implementation of the methods in Python.
Method 1: Using try-except Block
The try block contains the actual functionality of the code that is to be executed and the except block handles the exception. Below are code examples with different exceptions that occur.
Example 1: Value Error
The code below demonstrates that when a number is divided by 0. Python throws the exception of “division by zero”.
try:
x=3
print("The result is :", x/0)
except Exception as e:
print(e)
print('Execution Completed')
Output
The output below shows the exception of “division by zero”.
Method 2: Index Out of Range in List
The index out-of-range exception occurs when the index provided exceeds the maximum index of the list. The code is depicted below.
try:
#Declare a list in the try block
my_list = ["Python", "Java", "Javascript", "C++"]
print(my_list[6])
except Exception as e:
print(e)
print('Code Executed')
In the above code:
- The list is declared as “my_list” and four elements are passed in the list.
- The print() function contains the index as “6”.
- The exception is printed as “e” and the code ends.
Output
The below output depicts that the exception occurred as “ Index out of range for list”.
Method 3: Using traceback in Python
The term “traceback” is self-explanatory since it traces the line with the error and returns the exception using the except block of Python.
import traceback
def example1():
return 11 / 0
def main():
try:
example1()
except Exception as e:
traceback.print_exc()
if __name__ == '__main__':
main()
In the above code:
- The traceback module of Python is executed.
- A function is created a s”example1” that returns the result of 11/0.
- In the main function the try, except block is used to print the exception.
- In the last step, the main() method of Python is called.
Output
The output below depicts that the ZeroDivisionError occurs when the value is divided by zero.
Method 4: Using logging.exception in Python
The method adds the exception information along with the message in Python. It logs the message with “ERROR”. The below code implements the logging.exception() to print the exception.
#Import the logging module of Pythonimport logging
try:
#Declare a list in the try block
my_list = ["Python", "Java", "Javascript", "C++"]
print(my_list[4])
except Exception as e:
#Print the exception
logging.exception("An Exception occurred")
In the above Python code:
- The logging module of Python is imported.
- In the next step, the list is declared as “my_list” which contains four elements with indexes in the range of 0 to 3.
- The print() function passes an index value of 4.
- The except block contains the logging.exception() that prints the exception.
Output
The output below shows that the index of the list is out of range and the exception message is printed using the logging module.
Conclusion
The exception is the error while executing the code in Python. These are handled using three different which include try-except block, traceback method, and logging.exception() method. In this article, we have demonstrated the implementation of different methods to print the exception in Python.