0
0
Pythonprogramming~30 mins

Handling specific exceptions in Python - Mini Project: Build & Apply

Choose your learning style9 modes available
Handling specific exceptions
📖 Scenario: Imagine you are writing a small program that asks a user to enter two numbers and divides the first number by the second. Sometimes users might enter wrong data or try to divide by zero, which causes errors. We want to handle these errors carefully so the program does not crash and gives friendly messages.
🎯 Goal: You will build a program that safely divides two numbers by handling specific errors: ValueError when the input is not a number, and ZeroDivisionError when dividing by zero.
📋 What You'll Learn
Create two variables to store user input as numbers
Add a try-except block to catch ValueError and ZeroDivisionError
Print a friendly message for each specific error
Print the division result if no error occurs
💡 Why This Matters
🌍 Real World
Handling specific exceptions helps programs run smoothly even when users make mistakes, like entering wrong data or dividing by zero.
💼 Career
Knowing how to catch and handle errors is essential for writing reliable software that does not crash unexpectedly.
Progress0 / 4 steps
1
DATA SETUP: Create variables for user input
Create two variables called num1 and num2 by converting the strings '10' and '0' to integers using int().
Python
Need a hint?

Use int('10') to convert the string '10' to the number 10.

2
CONFIGURATION: Prepare for error handling
Create a variable called result and set it to None. This will hold the division result later.
Python
Need a hint?

Set result = None before trying the division.

3
CORE LOGIC: Use try-except to handle specific exceptions
Write a try block where you divide num1 by num2 and assign it to result. Add two except blocks: one for ZeroDivisionError that prints 'Cannot divide by zero.' and one for ValueError that prints 'Invalid number input.'.
Python
Need a hint?

Put the division inside try: and catch errors with except ZeroDivisionError: and except ValueError:.

4
OUTPUT: Print the division result if no error
After the try-except blocks, write an if statement that checks if result is not None. If so, print f'Result: {result}' to show the division result.
Python
Need a hint?

Use if result is not None: to check before printing.