|
प्रश्न 1. Python में Error Handle करने के लिए क्या उपयोग होता है? |
|
प्रश्न 4. स्वयं Exception Generate करने के लिए कौन-सा Keyword है? |
|
प्रश्न 6. गलत Integer Conversion पर कौन-सा Exception आ सकता है? |
Program चलाते समय कई बार ऐसी परिस्थितियाँ आती हैं जिनके कारण Program सामान्य रूप से Execute नहीं हो पाता। जैसे गलत Input देना, ऐसी File खोलना जो मौजूद नहीं है, किसी Number को Zero से Divide करना या गलत Data Type का उपयोग करना।
ऐसी समस्याओं को Python में Exception कहा जाता है।
Python में Exceptions को Handle करने के लिए Exception Handling का उपयोग किया जाता है।
इसके प्रमुख Keywords हैं—
- try
- except
- else
- finally
- raise
Program में होने वाली समस्या को सामान्य रूप से Error कहा जाता है, लेकिन Python में Runtime के दौरान उत्पन्न होने वाली कई समस्याएँ Exceptions के रूप में आती हैं जिन्हें Program में Handle किया जा सकता है।
उदाहरण:
print(10 / 0)
यहाँ ZeroDivisionError उत्पन्न होगा।
Exception Handling क्यों आवश्यक है?
यदि किसी Program में Exception Handle नहीं किया गया तो Program अचानक Terminate हो सकता है।
Exception Handling की सहायता से हम—
- Error को Control कर सकते हैं।
- User को उचित Message दे सकते हैं।
- Program को अचानक बंद होने से बचा सकते हैं।
- Alternative Code Execute कर सकते हैं।
- Cleanup Operations कर सकते हैं।
जिस Code में Exception आने की संभावना हो उसे try Block में लिखा जाता है।
try:
x = 10 / 0
लेकिन केवल try लिखना पर्याप्त नहीं है। इसके साथ except या अन्य उचित Clause होना चाहिए।
except Exception आने पर Execute होता है।
try:
x = 10 / 0
except:
print("An error occurred")
Output:
An error occurred
try:
number = int(input("Enter a number: "))
print(10 / number)
except:
print("Invalid input or division error")
सभी Exceptions को एक ही except में पकड़ने के बजाय Specific Exception Handle करना बेहतर होता है।
try:
number = int(input("Enter number: "))
print(10 / number)
except ValueError:
print("Please enter a valid number")
except ZeroDivisionError:
print("Number cannot be zero")
जब सही Type की आवश्यकता हो लेकिन Value गलत हो, तब ValueError आ सकता है।
number = int("abc")
यहाँ "abc" को Integer में Convert नहीं किया जा सकता।
जब किसी Number को Zero से Divide किया जाता है।
try:
result = 10 / 0
except ZeroDivisionError:
print("Cannot divide by zero")
जब दो Incompatible Data Types के बीच गलत Operation किया जाता है।
try:
result = "10" + 5
except TypeError:
print("Invalid data types")
जब किसी ऐसे Variable का उपयोग किया जाए जो Defined नहीं है।
try:
print(total)
except NameError:
print("Variable is not defined")
जब List या Sequence में Invalid Index Access किया जाता है।
numbers = [10, 20, 30]
try:
print(numbers[5])
except IndexError:
print("Index does not exist")
Dictionary में ऐसा Key Access करने पर जो मौजूद नहीं है।
student = {
"name": "Rahul",
"age": 20
}
try:
print(student["city"])
except KeyError:
print("Key not found")
जब ऐसी File Open करने की कोशिश की जाए जो मौजूद नहीं है।
try:
with open("abc.txt", "r") as file:
print(file.read())
except FileNotFoundError:
print("File not found")
except Exception as e की सहायता से Exception की जानकारी प्राप्त की जा सकती है।
try:
print(10 / 0)
except Exception as e:
print("Error:", e)
Output:
Error: division by zero
एक ही except में कई Exception Types भी दिए जा सकते हैं।
try:
number = int(input("Enter number: "))
print(100 / number)
except (ValueError, ZeroDivisionError):
print("Invalid input")
else Block तब Execute होता है जब try Block में कोई Exception नहीं आता।
try:
number = int(input("Enter number: "))
result = 100 / number
except ZeroDivisionError:
print("Cannot divide by zero")
else:
print("Result:", result)
finally Block सामान्यतः हर स्थिति में Execute होता है—Exception आए या न आए।
try:
print(10 / 2)
except ZeroDivisionError:
print("Error")
finally:
print("Program finished")
Output:
5.0
Program finished
इनका Basic Structure:
try:
# Risky Code
except:
# Error Handling
else:
# No Exception
finally:
# Always Execute
raise का उपयोग हम स्वयं Exception Generate करने के लिए कर सकते हैं।
age = 15
if age < 18:
raise ValueError("Age must be 18 or above")
raise के साथ Exception Handle करना
try:
age = int(input("Enter age: "))
if age < 18:
raise ValueError("You are not eligible")
print("Eligible")
except ValueError as e:
print("Error:", e)
हम अपनी आवश्यकता के अनुसार Custom Exception Class भी बना सकते हैं।
class AgeError(Exception):
pass
अब इसका उपयोग—
try:
age = int(input("Enter age: "))
if age < 18:
raise AgeError("Age must be 18 or above")
print("Eligible")
except AgeError as e:
print(e)
एक try के अंदर दूसरा try Block भी हो सकता है।
try:
number = int(input("Enter number: "))
try:
print(100 / number)
except ZeroDivisionError:
print("Cannot divide by zero")
except ValueError:
print("Invalid number")
Practical Program 1 – Division Calculator
try:
a = int(input("Enter first number: "))
b = int(input("Enter second number: "))
result = a / b
except ValueError:
print("Please enter numbers only")
except ZeroDivisionError:
print("Cannot divide by zero")
else:
print("Result:", result)
finally:
print("Calculation completed")
Practical Program 2 – Safe Integer Input
try:
number = int(input("Enter an integer: "))
print("You entered:", number)
except ValueError:
print("Invalid integer")
Practical Program 3 – File Handling with Exception
try:
with open("student.txt", "r", encoding="utf-8") as file:
data = file.read()
print(data)
except FileNotFoundError:
print("Student file does not exist")
Practical Program 4 – List Index
numbers = [10, 20, 30]
try:
index = int(input("Enter index: "))
print(numbers[index])
except ValueError:
print("Enter a valid integer")
except IndexError:
print("Index out of range")
Practical Program 5 – Dictionary
student = {
"name": "Rahul",
"age": 20
}
try:
key = input("Enter key: ")
print(student[key])
except KeyError:
print("Key not found")
Practical Program 6 – Multiple Exception Handling
try:
a = int(input("Enter first number: "))
b = int(input("Enter second number: "))
print(a / b)
except (ValueError, ZeroDivisionError):
print("Invalid input or division by zero")
Practical Program 7 – Age Validation
try:
age = int(input("Enter age: "))
if age < 0:
raise ValueError("Age cannot be negative")
print("Valid Age")
except ValueError as e:
print("Error:", e)
Practical Program 8 – Login Attempts
correct_password = "python123"
try:
password = input("Enter password: ")
if password != correct_password:
raise ValueError("Incorrect password")
print("Login successful")
except ValueError as e:
print("Login failed:", e)
Python में कई Exceptions एक Hierarchy में व्यवस्थित हैं।
Basic Structure:
BaseException
|
└── Exception
|
├── ValueError
├── TypeError
├── IndexError
├── KeyError
├── NameError
├── OSError
└── ...
इसलिए सामान्य Exception Handling में Exception का उपयोग कई Standard Exceptions को Handle करने के लिए किया जा सकता है।
except: और except Exception में अंतर
try:
...
except:
...
यह बहुत व्यापक तरीके से Exceptions को पकड़ सकता है।
try:
...
except Exception as e:
print(e)
Application Code में सामान्य Runtime Exceptions को Handle करने के लिए यह अक्सर अधिक स्पष्ट विकल्प होता है।
Exception Handling की Best Practices
except ValueError:
यह केवल जरूरी Exception को Handle करता है।
except:
pass
ऐसा करने से वास्तविक समस्या छिप सकती है।
except FileNotFoundError:
print("Student file was not found.")
Database Connection, File या अन्य Resources से संबंधित Cleanup में finally उपयोगी हो सकता है।
with open("data.txt", "r") as file:
data = file.read()
try
|
↓
Exception आया?
/ \
Yes No
| |
↓ ↓
except else
\ /
\ /
↓ ↓
finally
परीक्षा की दृष्टि से महत्वपूर्ण तथ्य
- Exception Handling के लिए try और except का उपयोग किया जाता है।
- try में संभावित Error वाला Code लिखा जाता है।
- except Exception को Handle करता है।
- else तब Execute होता है जब Exception नहीं आता।
- finally सामान्यतः हर स्थिति में Execute होता है।
- raise का उपयोग स्वयं Exception Generate करने के लिए किया जाता है।
- ValueError गलत Value के लिए आ सकता है।
- TypeError गलत Data Type Operation में आ सकता है।
- ZeroDivisionError Zero से Division पर आता है।
- IndexError Invalid List/Sequence Index पर आता है।
- KeyError Missing Dictionary Key पर आता है।
- FileNotFoundError Missing File पर आ सकता है।
- Custom Exception बनाने के लिए Exception Class को Inherit किया जा सकता है।
प्रश्न 1. Python में Error Handle करने के लिए क्या उपयोग होता है?
try-except
प्रश्न 2. कौन-सा Block हमेशा Execute होता है?
finally
प्रश्न 3. else कब Execute होता है?
जब try Block में कोई Exception नहीं आता।
प्रश्न 4. स्वयं Exception Generate करने के लिए कौन-सा Keyword है?
raise
प्रश्न 5. Zero से Divide करने पर कौन-सा Exception आता है?
ZeroDivisionError
प्रश्न 6. गलत Integer Conversion पर कौन-सा Exception आ सकता है?
ValueError
प्रश्न 7. List के गलत Index पर कौन-सा Exception आता है?
IndexError
- try → Risky Code
- except → Exception Handle
- else → No Exception होने पर
- finally → Cleanup/Final Code
- raise → Manually Exception
- ValueError → Invalid Value
- TypeError → Invalid Type Operation
- ZeroDivisionError → Zero Division
- IndexError → Invalid Index
- KeyError → Missing Dictionary Key
- FileNotFoundError → File नहीं मिली
अगला अध्याय —Python Modules & Packages
इसमें Module क्या है, import, from...import, as, Built-in Modules, User-Defined Modules, Packages, __name__, __main__ और Practical Programs विस्तार से होंगे।