Handle division by zero

EasyException Handling Programs · 1 of 20

Write a Python program that divides two numbers and prints a friendly message when the divisor is 0.

Advertisement
Input
(10, 2), (5, 0)
Output
5.0 | cannot divide by zero

Approach

  1. Put the division in try and catch ZeroDivisionError.

Solution

Python
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.

More exception handling programs

← All 20 Exception Handling Programs

Leave a Comment