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 twoexcept
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
- Copy the code into a Python file (e.g.,
exception_handling.py
). - Open a terminal or command prompt.
- Navigate to the directory where your Python file is saved.
- Run the program by typing
python exception_handling.py
(orpython3 exception_handling.py
depending on your setup). - Follow the on-screen prompt to input a number and see how the program handles different cases.