Python

 

Introduction

Exception handling is a critical concept in Python that allows you to manage runtime errors effectively. Instead of letting your program crash when it encounters unexpected issues, Python allows you to catch these exceptions and handle them gracefully. The try, except, and finally blocks are used to catch exceptions and ensure the program can recover or give appropriate feedback to the user.

Objective

The objective of this topic is to provide a clear understanding of how Python’s exception handling mechanism works using the try, except, and finally blocks. You’ll learn how to write Python programs that handle errors safely and how to ensure that important cleanup code always runs, whether or not an exception occurs.

Python Code Example


try:
    # Prompt user for input
    number = int(input("Enter a number: "))
    result = 10 / number
    print(f"The result of dividing 10 by {number} is {result}")

except ZeroDivisionError:
    print("Error: You can't divide by zero!")

except ValueError:
    print("Error: Invalid input, please enter a valid integer.")

finally:
    print("Execution completed.")

Explanation of Program Structure

This Python program demonstrates how to handle different types of exceptions and ensure proper cleanup:

  • Try Block: The try block contains the code that may potentially raise an exception. In this case, we are asking the user to enter a number and attempting to divide 10 by that number.
  • Except Block: The except block catches specific exceptions. There are two except blocks here: one to catch division by zero errors (ZeroDivisionError) and another to handle invalid input (ValueError).
  • Finally Block: The finally block always executes, regardless of whether an exception occurred or not. It’s used for cleanup actions like closing files or releasing resources. In this case, it prints “Execution completed” to signify the program’s end.

How to Run the Program

  1. Copy the code into a Python file (e.g., exception_handling.py).
  2. Open a terminal or command prompt.
  3. Navigate to the directory where your Python file is saved.
  4. Run the program by typing python exception_handling.py (or python3 exception_handling.py depending on your setup).
  5. Follow the on-screen prompt to input a number and see how the program handles different cases.
© 2025 Learn Programming. All Rights Reserved.

 

By Aditya Bhuyan

I work as a cloud specialist. In addition to being an architect and SRE specialist, I work as a cloud engineer and developer. I have assisted my clients in converting their antiquated programmes into contemporary microservices that operate on various cloud computing platforms such as AWS, GCP, Azure, or VMware Tanzu, as well as orchestration systems such as Docker Swarm or Kubernetes. For over twenty years, I have been employed in the IT sector as a Java developer, J2EE architect, scrum master, and instructor. I write about Cloud Native and Cloud often. Bangalore, India is where my family and I call home. I maintain my physical and mental fitness by doing a lot of yoga and meditation.

Leave a Reply

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

error

Enjoy this blog? Please spread the word :)