Introduction
Programming करते समय कई बार program में errors आ जाते हैं, जिससे program अचानक रुक जाता है।
इन errors को Python में Exceptions कहा जाता है।
Exception handling की मदद से हम इन errors को handle कर सकते हैं, ताकि program crash न हो और smoothly चलता रहे।
Exception क्या होता है
Exception एक ऐसी error होती है, जो program run होने के दौरान (runtime) आती है।
जब exception आता है, तो program का normal flow रुक जाता है।
Example (Without Handling)
num = int(input("Enter number: "))
print(10 / num)
अगर user 0 input देता है, तो error आएगा:
ZeroDivisionError
Common Types of Exceptions
- ZeroDivisionError → जब किसी number को 0 से divide करते हैं
- ValueError → जब गलत type का input देते हैं
- TypeError → जब गलत data types use होते हैं
- FileNotFoundError → जब file exist नहीं करती
Exception क्यों important है
- Program crash होने से बचता है
- User experience बेहतर होता है
- Errors को handle किया जा सकता है
try और except block
Exception को handle करने के लिए try और except का use किया जाता है।
try:
# risky code
except:
# error handling
Example
try:
num = int(input("Enter number: "))
print(10 / num)
except:
print("Error occurred")
Specific Exception Handling
हम specific error भी handle कर सकते हैं:
try:
num = int(input("Enter number: "))
print(10 / num)
except ZeroDivisionError:
print("Cannot divide by zero")
except ValueError:
print("Invalid input")
else block
अगर error नहीं आता, तो else block execute होता है।
try:
num = int(input("Enter number: "))
print(10 / num)
except:
print("Error")
else:
print("Success")
finally block
finally block हमेशा execute होता है, चाहे error आए या नहीं।
try:
print("Hello")
except:
print("Error")
finally:
print("Program ended")
Real-life Example: Safe division
try:
a = int(input("Enter first number: "))
b = int(input("Enter second number: "))
print(a / b)
except ZeroDivisionError:
print("Cannot divide by zero")
Real-life Example: File handling error
try:
file = open("data.txt", "r")
print(file.read())
except FileNotFoundError:
print("File not found")
Common mistakes
- try block के बिना except लिखना
- सभी errors को generic except से handle करना
- error message न देना
Mini Program
try:
num = int(input("Enter number: "))
print(num * 2)
except ValueError:
print("Please enter a valid number")
Summary
Exceptions Python में runtime errors को handle करने का तरीका है।
यह program को crash होने से बचाता है और उसे safe बनाता है।