Statement
Solution
Python Exercise 7.1: Safe Divider
Error handling is a critical skill in Python programming. Write a program that safely divides two numbers by catching potential runtime errors using try/except blocks.
Your program should:
- Ask the user to enter two numbers: a numerator and a denominator.
- Use a
try/exceptblock to attempt the division. - Catch a
ZeroDivisionErrorif the denominator is0and print an appropriate error message. - Catch a
ValueErrorif the user enters a non-numeric value and print an appropriate error message. - If the division is successful, print the result.
Sample Interaction 1 (Success):
Input
Output
10
2
Enter numerator: 10
Enter denominator: 2
Result: 5.0
Sample Interaction 2 (ZeroDivisionError):
Input
Output
10
0
Enter numerator: 10
Enter denominator: 0
Error: Cannot divide by zero.
Sample Interaction 3 (ValueError):
Input
Output
ten
2
Enter numerator: ten
Enter denominator: 2
Error: Invalid input. Please enter numeric values.
Solution
We wrap the risky operations (conversion and division) inside a try block and handle each specific error type in its own except clause.
try:
numerator = float(input("Enter numerator: "))
denominator = float(input("Enter denominator: "))
result = numerator / denominator
print(f"Result: {result}")
except ZeroDivisionError:
print("Error: Cannot divide by zero.")
except ValueError:
print("Error: Invalid input. Please enter numeric values.")
Key Concepts:
tryblock contains code that might raise an exception.except ExceptionTypecatches a specific error and runs the handler code.ZeroDivisionErroris raised automatically by Python when dividing by zero.ValueErroris raised whenfloat()receives a non-numeric string.- You can chain multiple
exceptblocks to handle different error types separately.
Test Console
Run code to see output...