Jump into concepts and practice - no test required
or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Common exception types
📖 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 cause errors like dividing by zero. We want to learn how to handle these common mistakes using exceptions.
🎯 Goal: You will create a program that safely divides two numbers entered by the user. You will handle common errors like entering text instead of numbers and dividing by zero, so the program does not crash and shows friendly messages.
📋 What You'll Learn
Create variables num1_str and num2_str to store two inputs entered by the user
Create a variable to store the result of division
Use try-except blocks to catch ValueError and ZeroDivisionError
Print the result if division is successful
Print clear error messages if exceptions occur
💡 Why This Matters
🌍 Real World
Handling errors like invalid input or division by zero is common in programs that take user input or do calculations. This makes programs more user-friendly and reliable.
💼 Career
Knowing how to catch and handle exceptions is a basic skill for software developers, especially when building applications that interact with users or external data.
Progress0 / 4 steps
1
DATA SETUP: Get two inputs from the user
Create two variables called num1_str and num2_str. Use input() to get values from the user.
Python
Hint
Use input() to store the user's input as strings in num1_str and num2_str.
2
CONFIGURATION: Prepare a variable for the division result
Create a variable called result and set it to None. This will hold the division result later.
Python
Hint
Set result to None before doing the division.
3
CORE LOGIC: Use try-except to divide and catch errors
Use a try block to convert num1_str and num2_str to integers num1 and num2, divide num1 by num2 and store the result in result. Add except ValueError to catch invalid number inputs and except ZeroDivisionError to catch division by zero. Print a friendly message inside each except block.
Python
Hint
Put the int() conversions and division inside try. Catch ValueError and ZeroDivisionError with except blocks.
4
OUTPUT: Print the division result if successful
After the try-except blocks, write a print() statement that shows result only if it is not None. Use an if statement to check this.
Python
Hint
Check if result is not None before printing it.
Practice
(1/5)
1. Which exception is raised when you try to divide a number by zero in Python?
easy
A. ValueError
B. ZeroDivisionError
C. IndexError
D. TypeError
Solution
Step 1: Understand division by zero
Dividing any number by zero is mathematically undefined and causes an error in Python.
Step 2: Identify the exception type
Python raises a ZeroDivisionError when division by zero occurs.
Final Answer:
ZeroDivisionError -> Option B
Quick Check:
Division by zero = ZeroDivisionError [OK]
Hint: Division by zero always raises ZeroDivisionError [OK]
Common Mistakes:
Confusing ZeroDivisionError with ValueError
Thinking IndexError occurs for division
Assuming TypeError is raised for zero division
2. Which of the following code snippets will raise a ValueError?
easy
A. open('file.txt')
B. 5 / 0
C. my_list[10] where my_list has 5 elements
D. int('abc')
Solution
Step 1: Analyze each option for ValueError
int('abc') tries to convert a non-numeric string to int, which causes ValueError.
Step 2: Check other options for different exceptions
5 / 0 causes ZeroDivisionError, C causes IndexError, A may cause FileNotFoundError.
Final Answer:
int('abc') -> Option D
Quick Check:
Invalid int conversion = ValueError [OK]
Hint: ValueError occurs when conversion or value is invalid [OK]
Common Mistakes:
Confusing ZeroDivisionError with ValueError
Assuming file open errors cause ValueError
Mixing IndexError with ValueError
3. What will be the output of this code?
my_list = [1, 2, 3]
print(my_list[3])
medium
A. IndexError
B. 3
C. None
D. ValueError
Solution
Step 1: Understand list indexing
List indices start at 0, so valid indices for my_list are 0, 1, 2.
Step 2: Accessing index 3
Index 3 is out of range, so Python raises an IndexError.
Final Answer:
IndexError -> Option A
Quick Check:
Out of range index = IndexError [OK]
Hint: Accessing invalid list index raises IndexError [OK]
Common Mistakes:
Thinking it returns last element
Assuming None is returned for invalid index
Confusing IndexError with ValueError
4. Identify the error in this code snippet:
try:
x = int('hello')
except ZeroDivisionError:
print('Cannot divide by zero')
medium
A. Wrong exception caught, should catch ValueError
B. SyntaxError due to missing colon
C. No error, code runs fine
D. ZeroDivisionError will be raised
Solution
Step 1: Analyze the try block
int('hello') raises ValueError because 'hello' cannot convert to int.
Step 2: Check except block
Except block catches ZeroDivisionError, which does not handle ValueError, so error is uncaught.
Final Answer:
Wrong exception caught, should catch ValueError -> Option A
Quick Check:
Exception type mismatch = catch correct exception [OK]
Hint: Catch the exact exception your code may raise [OK]
Common Mistakes:
Catching wrong exception type
Assuming code runs without error
Confusing syntax errors with exception handling
5. You want to safely convert user input to an integer and print it. Which code correctly handles invalid input without crashing?
hard
A. try:
num = int(input())
except ZeroDivisionError:
print('Invalid number')
B. num = int(input())
print(num)
C. try:
num = int(input())
except ValueError:
print('Invalid number')
D. num = input()
print(int(num))
Solution
Step 1: Understand input conversion risks
User input may not be a valid integer, causing ValueError on conversion.
Step 2: Check exception handling
try:
num = int(input())
except ValueError:
print('Invalid number') uses try-except to catch ValueError and print a message, preventing crash.
Final Answer:
try-except catching ValueError with message -> Option C
Quick Check:
Handle invalid input with ValueError catch [OK]
Hint: Use try-except to catch ValueError on int conversion [OK]
Common Mistakes:
Not catching exceptions causing program crash
Catching wrong exception type like ZeroDivisionError