Python Practice › Exception Handling Programs › Program 1
Handle division by zero
Write a Python program that divides two numbers and prints a friendly message when the divisor is 0.
Input
(10, 2), (5, 0)
Output
5.0 | cannot divide by zero
Approach
- Put the division in
tryand catchZeroDivisionError.
Solution
def safe_divide(a, b): try: return a / b except ZeroDivisionError: return "cannot divide by zero" print(safe_divide(10, 2), "|", safe_divide(5, 0))Output
5.0 | cannot divide by zero
Line by line
Lines 2-5
Only the division is inside try; the specific exception is caught, so other bugs still show up.
Learn the concept
New to this topic? Read the lesson, then come back.