Divide two numbers and handle errors with try, except and finally
Expt. No.05
Page No.10
Exception handling
Aim
To write a Python program that divides two numbers entered by the user and handles ZeroDivisionError and ValueError using try-except-finally.
Concepts used
Algorithm
- In a try block, input two integers and display their quotient.
- If the divisor is 0, the ZeroDivisionError block displays a message.
- If the input is not a whole number, the ValueError block displays a message.
- The finally block always displays that the program has finished.
Program
# Division with exception handling try: a = int(input("Enter the dividend: ")) b = int(input("Enter the divisor : ")) print("Quotient:", a / b)except ZeroDivisionError: print("Error: the divisor cannot be zero")except ValueError: print("Error: please enter whole numbers only")finally: print("Division program finished")
A marked line continues the line above it. In your file, write it on the same line.
Output
Run 1
$ python exception_handling_division.py
Enter the dividend: 45
Enter the divisor : 9
Quotient: 5.0
Division program finished
Run 2
$ python exception_handling_division.py
Enter the dividend: 45
Enter the divisor : 0
Error: the divisor cannot be zero
Division program finished
Run 3
$ python exception_handling_division.py
Enter the dividend: abc
Error: please enter whole numbers only
Division program finished
✓ Printed by running this program, not typed by hand.
Result
45 ÷ 9 gave 5.0. Dividing by 0 was caught by the ZeroDivisionError block, and typing "abc" was caught by the ValueError block before the divisor was even asked for. The finally block ran in all three cases.
Viva voce: what the examiner may ask
01What is an exception?
An error that occurs while the program is running, such as dividing by zero.
02When does the finally block run?
Always: whether an exception occurred or not.
03Why was the divisor not asked for in the third run?
int("abc") raised ValueError on the first line, so control jumped straight to the matching except block.
04What happens if an exception has no matching except block?
The program stops and Python displays the error message (traceback).
Variations for the lab test
- Add an
elseblock that prints "No errors" when the division works. - Keep asking until the user enters a valid divisor.
- Handle the error when a list index is out of range.
! Common mistake Putting a general
except: before except ZeroDivisionError: catches every error first, so the specific message is never shown.