How to do exception handling in python?

By | January 29, 2024

Exception handling in Python is done using the try, except, else, and finally blocks. Here’s a basic structure of a try-except block:

try:
    # Code that might raise an exception
    result = 10 / 0  # Example: Division by zero
except ExceptionType as e:
    # Handle the exception
    print(f"An exception of type {type(e).__name__} occurred: {e}")
else:
    # Code to be executed if no exception occurs
    print("No exception occurred.")
finally:
    # Code that will be executed no matter what
    print("This code will always run.")

Let’s break down the components:

  • The try block contains the code that might raise an exception.
  • The except block catches and handles the exception. You can catch specific exception types or a general Exception type.
  • The else block contains code that will be executed if no exception occurs.
  • The finally block contains code that will be executed no matter what, whether an exception occurred or not.

Example with a specific exception:

try:
    num = int(input("Enter a number: "))
    result = 10 / num
except ValueError:
    print("Invalid input. Please enter a valid number.")
except ZeroDivisionError:
    print("Cannot divide by zero.")
else:
    print(f"Result: {result}")
finally:
    print("Execution completed.")

In this example:

  • If the user enters a non-numeric value, a ValueError is caught.
  • If the user enters 0, a ZeroDivisionError is caught.
  • If the user enters a valid number, the result is displayed in the else block.
  • The finally block ensures that the final message is printed regardless of the outcome.

You can customize exception handling based on the specific requirements of your code. It’s generally a good practice to catch only the exceptions you expect and handle them appropriately. Avoid catching overly broad exceptions unless necessary.

Leave a Reply

Your email address will not be published. Required fields are marked *