← Previous Module 7: File Handling & Error Handling Next →
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/except block to attempt the division.
  • Catch a ZeroDivisionError if the denominator is 0 and print an appropriate error message.
  • Catch a ValueError if 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:

  • try block contains code that might raise an exception.
  • except ExceptionType catches a specific error and runs the handler code.
  • ZeroDivisionError is raised automatically by Python when dividing by zero.
  • ValueError is raised when float() receives a non-numeric string.
  • You can chain multiple except blocks to handle different error types separately.
Python 3
Test Console
Run code to see output...

Go Beyond Learning. Get Job-Ready.

Build in-demand skills for today's jobs with free expert-led courses and practical AI tools.

Explore All Courses
Scroll to Top