Python Exception Handling Notes
Master Exception Handling in Python: learn try, except, else, and finally blocks to write crash-proof Python applications.
Author: By Instructor
1. What is Exception Handling & Why Use It?
Exception Handling allows a program to deal with runtime errors gracefully. Instead of terminating abnormally (crashing), Python redirects execution to an error-handling block.
Easy English Explanation
- try block: Contains risky code that might throw an error.
- except block: Executes if an error occurs inside the try block to handle it.
- else block: Executes ONLY if NO error occurs in the try block.
- finally block: ALWAYS executes regardless of whether an error occurred or not.
Hinglish Explanation
- try: Iska use tab hota hai jab code me error aane ka chance ho. Program crash hone se bach jata hai.
- except: Jab try block me error aata hai, to except block run ho kar error handle karta hai.
- else: else tab run hota hai jab try block me koi error na aaye.
- finally: finally hamesha run hota hai (chahe error aaye ya na aaye).
Basic Syntax:
try:
risky_statement()
except:
error_handling_statement()
2. Exception Handling Structure & Control Flow
CONTROL FLOW DIAGRAM
[ try block ]
↓
Was there an Error?
↙ ↘
(YES) (NO)
↓ ↓
[ except block ] [ else block ]
↘ ↙
↓
[ finally block (ALWAYS RUNS) ]
[ try block ]
↓
Was there an Error?
↙ ↘
(YES) (NO)
↓ ↓
[ except block ] [ else block ]
↘ ↙
↓
[ finally block (ALWAYS RUNS) ]
3. Example 1: Handling Division by Zero
Python Code - Division Error Handling
try:
a = 10
b = 0
print(a / b)
except:
print("Cannot divide by zero")
Output
Cannot divide by zero
Line-by-Line Breakdown
| Line | Code Snippet | Easy English Explanation | Hinglish Explanation |
|---|---|---|---|
| 1-4 | try: print(a / b) | Attempts to divide 10 by 0, which triggers a ZeroDivisionError. | 10 ko 0 se divide karne par error aata hai, to control sidhe except block me jata hai. |
| 5-6 | except: print(...) | Catches the division error and prints user-friendly error message instead of crashing. | Program crash nahi hua, iski jagah custom user-friendly message print ho gaya. |
4. Example 2: Handling User Input Error (ValueError)
Python Code - Input Validation
try:
num = int("abc")
print(num)
except ValueError:
print("Invalid input! Please enter a valid number.")
Output
Invalid input! Please enter a valid number.
Line-by-Line Breakdown
| Line | Code Snippet | Easy English Explanation | Hinglish Explanation |
|---|---|---|---|
| 2 | int("abc") | Converting non-numeric string "abc" to int raises a ValueError. | String "abc" ko integer me convert karte hi ValueError generate hota hai. |
| 4-5 | except ValueError: | Catches specifically ValueError and displays validation prompt. | Specifically ValueError ko catch karke invalid input alert show karta hai. |
5. Example 3: Handling Specific Exceptions
In Python, you can specify exact exception types like ZeroDivisionError, ValueError, or TypeError to handle different errors distinctly.
Python Code - Specific Exception Types
try:
a = 10
b = 0
print(a / b)
except ZeroDivisionError:
print("Division by zero error caught specifically!")
except ValueError:
print("Value error caught!")
Output
Division by zero error caught specifically!
6. Example 4: The try–except–else Block
The else block runs ONLY when the try block completes smoothly without any error.
Python Code - try-except-else
try:
num = int("100")
except ValueError:
print("Invalid input")
else:
print("Successfully entered number:", num)
Output
Successfully entered number: 100
7. Example 5: The try–except–finally Block
The finally block ALWAYS executes regardless of whether an exception was raised or handled.
Python Code - try-except-finally
try:
print(12 / 0)
except ZeroDivisionError:
print("Division Error caught!")
finally:
print("Program finished execution (Finally block always runs).")
Output
Division Error caught!
Program finished execution (Finally block always runs).
Program finished execution (Finally block always runs).
8. Summary of All Four Exception Blocks
| Block Name | Purpose & Role | When Does It Run? |
|---|---|---|
| try | Contains risky code that might raise an error | Runs first |
| except | Handles the error if one occurs | Runs ONLY if an error occurs in try |
| else | Executes success code when no error occurs | Runs ONLY if NO error occurs in try |
| finally | Performs cleanup operations (e.g. closing files) | ALWAYS runs (error or no error) |