Exceptions are events that can occur during the execution of a Python program that disrupt the normal flow of the program. Exceptions can be caused by a variety of factors, such as invalid input, division by zero, or accessing a nonexistent object.
When an exception occurs, the Python interpreter will stop the current execution of the program and raise an exception object. This exception object contains information about the exception, such as the type of exception, the line number where the exception occurred, and the message associated with the exception.
To print an exception in Python, you can use the print() function. The print() function can be used to print any object, including exception objects.
For example, the following code will print an exception that occurs when we try to divide by zero:
try: 10 / 0 except Exception as e: print(e)
This code will print the following output:
division by zero
The output of the print() function will vary depending on the type of exception that is raised. For example, if the exception is a KeyError, the output will be the key that was not found.
If you want to print more detailed information about an exception, you can use the traceback module. The traceback module provides a number of functions that can be used to print the stack trace of an exception.
For example, the following code will print the stack trace of an exception that occurs when we try to access a nonexistent object:
import traceback try: print(variable_that_does_not_exist) except Exception as e: print(traceback.format_exc())
This code will print the following output:
Traceback (most recent call last):
File “my_file.py”, line 10, in
print(variable_that_does_not_exist)
NameError: name ‘variable_that_does_not_exist’ is not defined
The traceback.format_exc() function will print a detailed stack trace of the exception. The stack trace will show the line numbers of the code where the exception occurred, as well as the function calls that were made leading up to the exception.