Introduction
In programming, exceptions are errors that occur during the execution of a program. One common exception is the ZeroDivisionError
, which occurs when a number is divided by zero. To handle such exceptions gracefully, Python provides a try-except block, which allows you to manage errors and prevent your program from crashing unexpectedly.
This tutorial will guide you through creating a Python program that handles division by zero using a try-except block.
Example:
- Operation:
10 / 0
- Exception:
ZeroDivisionError
- Program Output:
Error: Division by zero is not allowed.
Problem Statement
Create a Python program that:
- Prompts the user to input two numbers.
- Attempts to divide the first number by the second.
- Catches and handles the
ZeroDivisionError
if the second number is zero. - Prints an appropriate error message when the exception occurs.
Solution Steps
- Prompt for Input: Use the
input()
function to get two numbers from the user. - Attempt Division: Use a try-except block to attempt the division.
- Handle the Exception: Catch the
ZeroDivisionError
and print an error message. - Display the Result: If no exception occurs, display the result of the division.
Python Program
# Python Program to Handle Division by Zero Exception
# Author: https://www.rameshfadatare.com/
# Step 1: Prompt for Input
try:
numerator = float(input("Enter the numerator: "))
denominator = float(input("Enter the denominator: "))
# Step 2: Attempt Division
result = numerator / denominator
# Step 3: Handle the Exception
except ZeroDivisionError:
print("Error: Division by zero is not allowed.")
# Step 4: Display the Result
else:
print(f"The result is: {result}")
Explanation
Step 1: Prompt for Input
- The program prompts the user to input the numerator and the denominator using the
input()
function. The inputs are converted to floating-point numbers usingfloat()
.
Step 2: Attempt Division
- The division operation is attempted inside a
try
block. If the denominator is zero, Python raises aZeroDivisionError
.
Step 3: Handle the Exception
- The
except ZeroDivisionError
block catches theZeroDivisionError
if it occurs. When the exception is caught, an error message is printed to inform the user that division by zero is not allowed.
Step 4: Display the Result
- The
else
block is executed only if no exception occurs. It displays the result of the division.
Output Example
Example Output 1: Division by Zero
Enter the numerator: 10
Enter the denominator: 0
Error: Division by zero is not allowed.
Example Output 2: Valid Division
Enter the numerator: 10
Enter the denominator: 2
The result is: 5.0
Additional Examples
Example 1: Handling Multiple Exceptions
try:
numerator = float(input("Enter the numerator: "))
denominator = float(input("Enter the denominator: "))
result = numerator / denominator
except ZeroDivisionError:
print("Error: Division by zero is not allowed.")
except ValueError:
print("Error: Invalid input. Please enter numeric values.")
else:
print(f"The result is: {result}")
Output:
Enter the numerator: 10
Enter the denominator: abc
Error: Invalid input. Please enter numeric values.
- This example handles both
ZeroDivisionError
andValueError
(which occurs if the user inputs a non-numeric value).
Example 2: Using finally Block
try:
numerator = float(input("Enter the numerator: "))
denominator = float(input("Enter the denominator: "))
result = numerator / denominator
except ZeroDivisionError:
print("Error: Division by zero is not allowed.")
except ValueError:
print("Error: Invalid input. Please enter numeric values.")
else:
print(f"The result is: {result}")
finally:
print("Division operation completed.")
Output:
Enter the numerator: 10
Enter the denominator: 2
The result is: 5.0
Division operation completed.
- The
finally
block is executed regardless of whether an exception occurred, making it useful for cleanup actions.
Example 3: Raising a Custom Exception
def divide(numerator, denominator):
if denominator == 0:
raise ZeroDivisionError("Cannot divide by zero")
return numerator / denominator
try:
result = divide(10, 0)
except ZeroDivisionError as e:
print(e)
Output:
Cannot divide by zero
- This example demonstrates how to raise and handle a custom
ZeroDivisionError
.
Conclusion
This Python program demonstrates how to handle division by zero using exception handling. By using a try-except block, you can catch and manage exceptions like ZeroDivisionError
, preventing your program from crashing and providing a user-friendly error message instead. Exception handling is a crucial skill in Python programming, allowing you to write robust and error-resistant code.