Error और Exception Handling का मतलब है — प्रोग्राम में चलने के दौरान जो गलतियाँ (errors) आती हैं, उन्हें पहचानना और उनका सही तरीके से समाधान करना, ताकि प्रोग्राम क्रैश न हो।
🔹 Common Built-in Exceptions
| Exception Type | कब आता है? |
|---|---|
ZeroDivisionError | जब किसी संख्या को 0 से भाग करते हैं |
ValueError | गलत value दी गई हो |
TypeError | गलत data type पर ऑपरेशन हो |
IndexError | लिस्ट के गलत इंडेक्स पर एक्सेस |
KeyError | डिक्शनरी में न होने वाली key |
FileNotFoundError | फ़ाइल नहीं मिली |
🔹 Multiple except blocks
आप एक से ज़्यादा errors को अलग-अलग handle कर सकते हैं:
try:
x = int("abc")
except ValueError:
print("Wrong input")
except TypeError:
print("Type issue")
except Exception as e:
print("Other issue:", e)
🔹 Using else and finally
elseblock तब चलेगा जब कोई exception न आए।finallyblock हमेशा चलता है, चाहे error आए या नहीं।
📌 उदाहरण:
try:
f = open("file.txt", "r")
data = f.read()
except FileNotFoundError:
print("File not found.")
else:
print("File read successfully.")
finally:
print("This block will always execute.")
🔹 Raising Custom Exception
आप खुद भी exception फेंक सकते हैं:
def check_age(age):
if age < 18:
raise ValueError("Age must be 18 or older!")
return "Access granted."
try:
print(check_age(20)) # Access granted.
print(check_age(16)) # Raises ValueError
except ValueError as e:
print(f"Error: {e}")
🖥️ GUI Calculator using tkinter with Error Handling
import tkinter as tk
from tkinter import messagebox
def calculate(operation):
try:
num1 = float(entry1.get())
num2 = float(entry2.get())
if operation == '+':
result = num1 + num2
elif operation == '-':
result = num1 - num2
elif operation == '*':
result = num1 * num2
elif operation == '/':
result = num1 / num2
else:
result = "Invalid Operation"
result_label.config(text="Result: " + str(result))
except ValueError:
messagebox.showerror("Input Error", "कृपया केवल संख्याएँ दर्ज करें।")
except ZeroDivisionError:
messagebox.showerror("Math Error", "0 से भाग नहीं कर सकते।")
except Exception as e:
messagebox.showerror("Unknown Error", str(e))
# GUI window बनाना
window = tk.Tk()
window.title("Simple Calculator")
window.geometry("300x250")
# Entry fields
tk.Label(window, text="पहली संख्या:").pack()
entry1 = tk.Entry(window)
entry1.pack()
tk.Label(window, text="दूसरी संख्या:").pack()
entry2 = tk.Entry(window)
entry2.pack()
# Operation buttons
tk.Label(window, text="ऑपरेशन चुनें:").pack(pady=5)
tk.Button(window, text="+", width=5, command=lambda: calculate('+')).pack()
tk.Button(window, text="-", width=5, command=lambda: calculate('-')).pack()
tk.Button(window, text="*", width=5, command=lambda: calculate('*')).pack()
tk.Button(window, text="/", width=5, command=lambda: calculate('/')).pack()
# Result label
result_label = tk.Label(window, text="Result: ")
result_label.pack(pady=10)
# Start GUI loop
window.mainloop()

Python allows you to define your own custom exception classes by creating a new class that inherits (directly or indirectly) from the built-in Exception class (or one of its subclasses). This makes your error handling more specific and informative.
class InvalidAgeError(Exception):
"""Custom exception for invalid age."""
def __init__(self, message="Age must be 18 or older!"):
self.message = message
return super().__init__(self.message)
def verify_age(age):
if age < 18:
raise InvalidAgeError() # Raise your custom exception
return "Welcome!"
try:
print(verify_age(16))
except InvalidAgeError as e:
print(f"Error: {e}")