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
Why Exceptions Occur
📖 Scenario: Imagine you are writing a simple program that asks a user to enter two numbers and divides the first number by the second. Sometimes, things can go wrong, like if the user types a word instead of a number or tries to divide by zero. These problems cause exceptions in the program.
🎯 Goal: You will create a small program that shows why exceptions happen by trying to divide two numbers. You will see what causes errors and how Python tells you about them.
📋 What You'll Learn
Create two variables with exact names and values
Add a variable to hold the divisor
Write code that divides the numbers and can cause an exception
Print the result or the error message
💡 Why This Matters
🌍 Real World
Handling exceptions is important in real programs to avoid crashes and give users helpful messages.
💼 Career
Knowing why exceptions occur and how to handle them is a key skill for all programmers to write reliable software.
Progress0 / 4 steps
1
Create two variables with numbers
Create two variables called num1 and num2 with the exact values 10 and 0 respectively.
Python
Hint
Use the equals sign = to assign values to variables.
2
Add a variable for the divisor
Create a variable called divisor and set it to the value of num2.
Python
Hint
Assign the value of num2 to divisor using =.
3
Divide the numbers to cause an exception
Write a line that divides num1 by divisor and stores the result in a variable called result.
Python
Hint
Use the division operator / to divide numbers.
4
Print the result or the error message
Use a try and except block to print result if division works, or print "Error: Division by zero is not allowed." if an exception occurs.
Python
Hint
Put the division inside try, and catch ZeroDivisionError in except.
Practice
(1/5)
1. Why do exceptions occur in a Python program?
easy
A. Because the program encounters an unexpected error during execution
B. Because the program runs perfectly without any errors
C. Because the program finishes all tasks successfully
D. Because the program has no code to execute
Solution
Step 1: Understand what exceptions mean
Exceptions happen when the program faces an unexpected problem it cannot handle normally.
Step 2: Identify the cause of exceptions
Unexpected errors like dividing by zero or accessing missing files cause exceptions.
Final Answer:
Because the program encounters an unexpected error during execution -> Option A
Quick Check:
Unexpected error = Exception occurs [OK]
Hint: Exceptions happen only when errors occur during running [OK]
Common Mistakes:
Thinking exceptions occur when program runs fine
Confusing exceptions with normal program flow
Believing exceptions happen without any error
2. Which of the following is the correct way to catch an exception in Python?
easy
A. try:
# code
except Exception:
# handle error
B. catch:
# code
try Exception:
# handle error
C. handle:
# code
catch Exception:
# handle error
D. try:
# code
catch Exception:
# handle error
Solution
Step 1: Recall Python syntax for exception handling
Python uses try to run code and except to catch errors.
Step 2: Match the correct syntax
try:
# code
except Exception:
# handle error uses try and except Exception, which is correct.
Final Answer:
try:\n # code\nexcept Exception:\n # handle error -> Option A
Quick Check:
Use try and except keywords [OK]
Hint: Remember: try and except catch errors in Python [OK]
Common Mistakes:
Using catch instead of except
Swapping try and except keywords
Incorrect keyword order or spelling
3. What will be the output of this code?
try:
x = 5 / 0
except ZeroDivisionError:
print('Cannot divide by zero')
medium
A. No output
B. 5
C. ZeroDivisionError
D. Cannot divide by zero
Solution
Step 1: Analyze the code inside try block
The code tries to divide 5 by 0, which causes a ZeroDivisionError.
Step 2: Check the except block
The except block catches ZeroDivisionError and prints 'Cannot divide by zero'.
Final Answer:
Cannot divide by zero -> Option D
Quick Check:
ZeroDivisionError caught prints message [OK]
Hint: Division by zero triggers ZeroDivisionError [OK]
The except line lacks a colon at the end, which is required in Python.
Step 2: Confirm other parts are correct
try keyword and exception type are correct; only colon is missing.
Final Answer:
Missing colon after except statement -> Option C
Quick Check:
except line must end with colon [OK]
Hint: Always put colon after except statement [OK]
Common Mistakes:
Forgetting colon after except
Assuming wrong exception type causes syntax error
Thinking try keyword is missing
5. You want to open a file and read its content, but the file might not exist. Which code correctly handles this exception?
hard
A. try:
with open('data.txt') as f:
print(f.read())
except:
pass
B. try:
with open('data.txt') as f:
print(f.read())
except FileNotFoundError:
print('File not found')
C. try:
with open('data.txt') as f:
print(f.read())
except ZeroDivisionError:
print('File not found')
D. with open('data.txt') as f:
print(f.read())
except FileNotFoundError:
print('File not found')
Solution
Step 1: Understand the problem
Opening a file that may not exist can cause FileNotFoundError.
Step 2: Check which option correctly catches FileNotFoundError
try:
with open('data.txt') as f:
print(f.read())
except FileNotFoundError:
print('File not found') uses try-except with FileNotFoundError and prints a message, which is correct.
Final Answer:
try:\n with open('data.txt') as f:\n print(f.read())\nexcept FileNotFoundError:\n print('File not found') -> Option B
Quick Check:
Catch FileNotFoundError to handle missing files [OK]
Hint: Catch FileNotFoundError to handle missing files [OK]