Exception HandlingIntermediate
1Question 1 of 2
pythonHow does Exception Handling work in Python with try, except, else, and finally?
Explanation & Concept
• `try`: The block of code to monitor for exceptions. • `except SpecificError`: Catches and handles specific error types. • `else`: Executes only if **no exception** was thrown in the `try` block. • `finally`: Executes unconditionally, regardless of whether exceptions were caught.
Code Example
python
def calculate_average(items):
try:
total = sum(items)
avg = total / len(items)
except ZeroDivisionError:
print("Cannot calculate average of an empty list.")
return 0
except TypeError as e:
print(f"Invalid item type: {e}")
return None
else:
print("Calculation successful!")
return avg
finally:
print("Operation completed.")How It Works & Key Takeaways
Using specific exception types prevents masking unexpected programming bugs that a bare `except:` would hide.