Sometimes, your program might run into problems. Handling specific exceptions helps you catch and fix only certain errors, so your program can keep running smoothly.
Handling specific exceptions 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 ExceptionType: # code to handle that specific error
Replace
ExceptionType with the specific error you want to catch, like ZeroDivisionError or FileNotFoundError.You can have multiple
except blocks to handle different errors separately.Examples
Python
try: x = 10 / 0 except ZeroDivisionError: print("Cannot divide by zero!")
Python
try: f = open('missing.txt') except FileNotFoundError: print("File not found.")
Python
try: num = int(input('Enter a number: ')) except ValueError: print("That's not a valid number.")
Sample Program
This program tries to divide two numbers. If the second number is zero, it catches the error and returns a friendly message instead of crashing.
Python
def divide_numbers(a, b): try: result = a / b except ZeroDivisionError: return "Error: Cannot divide by zero." else: return f"Result is {result}" print(divide_numbers(10, 2)) print(divide_numbers(5, 0))
Important Notes
Always catch the most specific exceptions you expect to handle.
Using a general except: without specifying the error can hide bugs and is not recommended.
You can use else: after try-except to run code only if no error happened.
Summary
Use try-except to catch specific errors and keep your program running.
Handle different errors with separate except blocks for clearer code.
Provide helpful messages or actions when errors happen to improve user experience.
Practice
1. What is the main purpose of using
try-except blocks in Python?easy
Solution
Step 1: Understand the role of try-except
Thetry-exceptblock is used to catch errors that happen during program execution.Step 2: Identify the benefit of catching errors
By catching errors, the program can handle them gracefully and continue running instead of crashing.Final Answer:
To catch and handle specific errors so the program doesn't crash -> Option AQuick Check:
try-except = catch errors [OK]
Hint: Try-except blocks catch errors to avoid crashes [OK]
Common Mistakes:
- Thinking try-except speeds up code
- Confusing try-except with comments
- Believing try-except creates functions
2. Which of the following is the correct syntax to catch a
ZeroDivisionError in Python?easy
Solution
Step 1: Check the correct keyword for catching exceptions
Python usesexceptto catch exceptions, notcatch.Step 2: Verify the exception name spelling
The correct exception name isZeroDivisionError, notZeroDivision.Final Answer:
try: x = 1/0 except ZeroDivisionError: print('Cannot divide by zero') -> Option CQuick Check:
Use except + exact exception name [OK]
Hint: Use except with exact exception name to catch errors [OK]
Common Mistakes:
- Using 'catch' instead of 'except'
- Misspelling exception names
- Using generic except without specifying error
3. What will be the output of this code?
try:
num = int('abc')
except ValueError:
print('Value error caught')
except TypeError:
print('Type error caught')medium
Solution
Step 1: Identify the error raised by int('abc')
Trying to convert 'abc' to int raises aValueError.Step 2: Match the error with except blocks
TheValueErroris caught by the first except block, so it prints 'Value error caught'.Final Answer:
Value error caught -> Option AQuick Check:
int('abc') = ValueError caught [OK]
Hint: Match error type to except block to find output [OK]
Common Mistakes:
- Confusing ValueError with TypeError
- Thinking program crashes without except
- Assuming no output if error caught
4. Find the error in this code and choose the correct fix:
try:
print(10 / 0)
except ZeroDivisionError, e:
print('Error:', e)medium
Solution
Step 1: Identify the syntax error in except clause
Python 3 requires 'as' to assign exception to a variable, not a comma.Step 2: Correct the except syntax
Replaceexcept ZeroDivisionError, e:withexcept ZeroDivisionError as e:.Final Answer:
Change except line to: except ZeroDivisionError as e: -> Option BQuick Check:
Use 'as' to assign exception variable [OK]
Hint: Use 'except Exception as e:' syntax in Python 3 [OK]
Common Mistakes:
- Using comma instead of 'as' in except
- Removing except block causing crash
- Wrong parentheses in except clause
5. You want to handle both
KeyError and IndexError in the same block. Which is the best way to write the except clause?hard
Solution
Step 1: Understand how to catch multiple exceptions
Python requires a tuple of exceptions inside parentheses to catch multiple exceptions in one block.Step 2: Identify correct tuple syntax
The correct syntax isexcept (KeyError, IndexError):to catch both exceptions.Final Answer:
except (KeyError, IndexError): print('Error caught') -> Option DQuick Check:
Use tuple in except to catch multiple exceptions [OK]
Hint: Use except (Error1, Error2): to catch multiple exceptions [OK]
Common Mistakes:
- Using 'or' or 'and' instead of tuple
- Using comma without parentheses
- Trying to catch exceptions separately without blocks
