Google News
logo
Python Program to When an error occurs, print a message
Certainly, here's a Python program that demonstrates how to catch and handle errors using try-except blocks :
try:
    # Your code goes here
except Exception as e:
    print(f"An error occurred: {e}")​

In the `try` block, you can put the code that you want to execute. If an error occurs within the `try` block, the program will jump to the `except` block. In the `except` block, you can handle the error and print a message.
For example, here's a program that attempts to divide a number by zero :
try:
    x = 5 / 0
except Exception as e:
    print(f"An error occurred: {e}")​

When this program is executed, it will print the following message :
An error occurred: division by zero​

This is because the `5 / 0` operation is not allowed in Python, and it raises a `ZeroDivisionError` exception. The `except` block catches this exception and prints an error message.