Module 10: Python Exception HandlingBeginner18 min read
Try, Except, Finally
Handle runtime errors gracefully and prevent application crashes.
Key Takeaways & Core Concepts
try: Contains code that might trigger an error.except: Executes if an error of matching type is raised.else: Executes only if no exceptions were raised in the try block.finally: Executes always, whether an exception occurred or not (great for cleanup).
Try, Except, Finally
### Exception Handling in Python
When an error occurs, Python normally stops and generates an error message (raises an exception). You can handle these exceptions using try, except, else, and finally blocks:
try: Contains code that might trigger an error.except: Executes if an error of matching type is raised.else: Executes only if no exceptions were raised in the try block.finally: Executes always, whether an exception occurred or not (great for cleanup).
PYTHON Code Example
1try:
2 number = int("invalid_number")
3except ValueError as e:
4 print("Caught conversion error:", e)
5else:
6 print("Conversion succeeded!")
7finally:
8 print("Cleanup operations completed.")
Click code or "Edit Code" to edit
Interactive Code Block•Tab = 4 spaces•Ctrl + Enter = Run
8 lines
Handling Multiple Exception Types
1def safe_divide(a, b):
2 try:
3 val_a = float(a)
4 val_b = float(b)
5 return val_a / val_b
6 except ZeroDivisionError:
7 return "Error: Cannot divide by zero"
8 except ValueError:
9 return "Error: Invalid numeric input"
10
11print(safe_divide(20, 4))
12print(safe_divide(10, 0))
13print(safe_divide("abc", 5))
Click code or "Edit Code" to edit
Interactive Code Block•Tab = 4 spaces•Ctrl + Enter = Run
13 lines
Note: Each except block catches only its corresponding exception type.
Practice & AssessmentPython Programming Tutorial
Test Your Understanding
Reinforce core concepts with interactive multiple-choice questions, live coding challenges, and top technical interview questions.
Your Current Score
0 / 0 correct(0 attempted)