Exceptions happen when something unexpected goes wrong while a program runs. They stop the normal flow so the problem can be fixed or handled.
Why exceptions occur in Python
Start learning this pattern below
Jump into concepts and practice - no test required
or
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Introduction
Syntax
Python
try: # code that might cause an error except SomeError: # code to handle the error
The try block contains code that might cause an error.
The except block runs if an error happens in the try block.
Examples
Python
try: x = 10 / 0 except ZeroDivisionError: print("Cannot divide by zero!")
Python
try: num = int(input("Enter a number: ")) except ValueError: print("That is not a valid number.")
Sample Program
This program tries to access a list item that is not there. It catches the error and prints a friendly message.
Python
try: numbers = [1, 2, 3] print(numbers[5]) except IndexError: print("Oops! That index does not exist.")
Important Notes
Exceptions help keep programs from crashing suddenly.
Always try to handle exceptions you expect to happen.
Use specific exception types to catch only the errors you want.
Summary
Exceptions happen when something unexpected goes wrong in the program.
Use try and except to catch and handle these errors.
Handling exceptions makes programs more reliable and user-friendly.
Practice
1. Why do exceptions occur in a Python program?
easy
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 AQuick 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
Solution
Step 1: Recall Python syntax for exception handling
Python usestryto run code andexceptto catch errors.Step 2: Match the correct syntax
try: # code except Exception: # handle error usestryandexcept Exception, which is correct.Final Answer:
try:\n # code\nexcept Exception:\n # handle error -> Option AQuick 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
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 DQuick Check:
ZeroDivisionError caught prints message [OK]
Hint: Division by zero triggers ZeroDivisionError [OK]
Common Mistakes:
- Expecting program to crash without output
- Confusing error name with printed message
- Ignoring except block handling
4. Find the error in this code snippet:
try:
print(10 / 2)
except ZeroDivisionError
print('Error')medium
Solution
Step 1: Check syntax of except statement
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 CQuick 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
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 BQuick Check:
Catch FileNotFoundError to handle missing files [OK]
Hint: Catch FileNotFoundError to handle missing files [OK]
Common Mistakes:
- Placing except outside try block
- Catching wrong exception type
- Ignoring exception handling completely
