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.
When you want to catch a mistake like dividing by zero and show a friendly message.
When reading a file that might not exist and you want to handle that case differently.
When converting user input to a number and want to catch invalid input errors.
When calling a function that might raise different errors and you want to handle each one separately.
Syntax
Python
try:
# code that might cause an errorexcept 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
This catches the error when dividing by zero and prints a message.
Python
try:
x = 10 / 0except ZeroDivisionError:
print("Cannot divide by zero!")
This handles the case when the file does not exist.
Python
try:
f = open('missing.txt')
except FileNotFoundError:
print("File not found.")
This catches errors when the user types something that is not a number.
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))
OutputSuccess
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/5)
1. What is the main purpose of using try-except blocks in Python?
easy
A. To catch and handle specific errors so the program doesn't crash
B. To speed up the program execution
C. To write comments inside the code
D. To create new functions automatically
Solution
Step 1: Understand the role of try-except
The try-except block 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 A
Quick 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
A. try:
x = 1/0
except:
print('Error')
B. try:
x = 1/0
catch ZeroDivisionError:
print('Cannot divide by zero')
C. try:
x = 1/0
except ZeroDivisionError:
print('Cannot divide by zero')
D. try:
x = 1/0
except ZeroDivision:
print('Cannot divide by zero')
Solution
Step 1: Check the correct keyword for catching exceptions
Python uses except to catch exceptions, not catch.
Step 2: Verify the exception name spelling
The correct exception name is ZeroDivisionError, not ZeroDivision.
Final Answer:
try:
x = 1/0
except ZeroDivisionError:
print('Cannot divide by zero') -> Option C
Quick Check:
Use except + exact exception name [OK]
Hint: Use except with exact exception name to catch errors [OK]