Generic exception handling helps your program catch any error that might happen, so it doesn't crash unexpectedly.
Generic exception handling 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 Exception: # code to run if any error happens
The try block contains code that might cause an error.
The except Exception block catches any error that is a subclass of Exception, which is most errors.
Examples
Python
try: x = 1 / 0 except Exception: print("Something went wrong")
Python
try: print(undefined_variable) except Exception as e: print(f"Error: {e}")
Sample Program
This program asks for a number and divides 10 by it. If the user enters zero or something not a number, it catches the error and shows a friendly message.
Python
try: number = int(input("Enter a number: ")) result = 10 / number print(f"10 divided by {number} is {result}") except Exception: print("Oops! Something went wrong.")
Important Notes
Using generic exception handling is helpful but can hide specific errors, so use it carefully.
You can get the error details by using except Exception as e and printing e.
Summary
Generic exception handling catches most errors to prevent crashes.
Use try and except Exception to handle errors simply.
Be careful not to hide important error details when using generic handling.
Practice
1. What does generic exception handling with
except Exception do in Python?easy
Solution
Step 1: Understand the role of
This clause catches exceptions that are instances of the Exception class or its subclasses, which covers most runtime errors.except ExceptionStep 2: Recognize its effect on program flow
By catching these exceptions, the program avoids crashing and can handle errors gracefully.Final Answer:
It catches most types of errors to prevent the program from crashing. -> Option CQuick Check:
Generic exception handling = catches most errors [OK]
Hint: Generic catch uses
except Exception to stop crashes [OK]Common Mistakes:
- Thinking it only catches syntax errors
- Believing it fixes errors automatically
- Assuming it ignores errors silently
2. Which of the following is the correct syntax to catch all exceptions in Python?
easy
Solution
Step 1: Identify correct exception syntax
In Python, to catch most exceptions, useexcept Exception:. The bareexcept:also catches exceptions but is less specific.Step 2: Check syntax correctness
try: pass except Exception: uses the correct keywordexceptwith the Exception class, which is the recommended way.Final Answer:
try:\n pass\nexcept Exception: -> Option DQuick Check:
Correct generic catch syntax = except Exception: [OK]
Hint: Use
except Exception: to catch most errors correctly [OK]Common Mistakes:
- Using
catchinstead ofexcept - Using undefined
Errorclass - Using bare except without colon
3. What will be the output of this code?
try:
x = 5 / 0
except Exception:
print("Error caught")
print("Done")medium
Solution
Step 1: Identify the error raised
The code tries to divide 5 by 0, which raises a ZeroDivisionError, a subclass of Exception.Step 2: Check exception handling and output
Theexcept Exceptionblock catches this error and prints "Error caught". Then the program continues and prints "Done".Final Answer:
Error caught\nDone -> Option BQuick Check:
ZeroDivisionError caught = prints error message and continues [OK]
Hint: Generic except catches ZeroDivisionError and prints message [OK]
Common Mistakes:
- Expecting program to crash with error message
- Thinking error message is printed automatically
- Missing that 'Done' prints after exception
4. Find the error in this code snippet:
try:
print(10 / 0)
except Exception
print("Caught error")medium
Solution
Step 1: Check syntax of except block
The except line is missing a colon at the end, which is required in Python syntax.Step 2: Confirm other parts are correct
Division by zero raises ZeroDivisionError, subclass of Exception, so it is caught. The print statement syntax is correct. Else clause is optional.Final Answer:
Missing colon after except Exception -> Option AQuick Check:
except line must end with colon : [OK]
Hint: Always put colon after except Exception: [OK]
Common Mistakes:
- Forgetting colon after except
- Thinking division by zero is uncaught
- Believing else clause is mandatory
5. You want to catch any error in a function but also print the error message. Which code correctly does this?
def safe_divide(a, b):
try:
return a / b
except Exception as e:
print(e)
return Nonehard
Solution
Step 1: Analyze the try-except block
The function tries to divide a by b. If any exception occurs, it is caught byexcept Exception as e.Step 2: Check error message printing and return
The caught exception is printed usingprint(e), then the function returns None to indicate failure.Final Answer:
This code catches all exceptions and prints the error message. -> Option AQuick Check:
except Exception as e prints error message [OK]
Hint: Use
except Exception as e to print error details [OK]Common Mistakes:
- Not using 'as e' to access error message
- Assuming only ZeroDivisionError is caught
- Missing return after exception
