Python Exception Handling क्या है? try, except, else & finally in Hindi | RBSE Class 12

इस लेख में: Python Errors और Exceptions क्या होते हैं, Exception Handling की जरूरत, try, except, else, finally और raise statements तथा ZeroDivisionError, ValueError, TypeError, NameError, IndexError और FileNotFoundError जैसे common errors को आसान Hindi में examples के साथ समझेंगे।

Python Exception Handling क्या है?

Program execute करते समय यदि कोई ऐसी स्थिति आती है जिससे program का normal execution बाधित हो जाता है, तो Python में उसे handle करने के लिए Exception Handling का उपयोग किया जाता है।

Exception Handling की सहायता से हम program में आने वाली कई runtime problems को नियंत्रित कर सकते हैं और user को उचित message दे सकते हैं।

Error और Exception में अंतर

Programming में Error और Exception related concepts हैं, लेकिन दोनों को एक ही चीज नहीं मानना चाहिए। Syntax error जैसी समस्या program के syntax में गलती के कारण होती है, जबकि कई runtime problems exceptions के रूप में दिखाई देती हैं जिन्हें program के flow में handle किया जा सकता है।

Python में Error का Example

print("Hello"

print("Python")

ऊपर code में closing parenthesis missing है। यह syntax error का उदाहरण है।

Exception का Simple Example

number = 10
result = number / 0

print(result)

यहाँ zero से division करने के कारण ZeroDivisionError उत्पन्न हो सकता है।

Exception Handling क्यों जरूरी है?

  • Program को unexpected situations से संभालने के लिए।
  • User-friendly error message देने के लिए।
  • Program को अचानक terminate होने से बचाने के लिए।
  • Runtime problems को appropriately handle करने के लिए।
  • Robust programs बनाने के लिए।
Important: Python में Exception Handling के लिए सबसे महत्वपूर्ण keywords try और except हैं।

try और except

try block में वह code लिखा जाता है जिसमें exception आने की संभावना हो सकती है। यदि exception आती है तो except block उसे handle कर सकता है।

Syntax

try:
    # risky code

except:
    # exception handling code

Example

try:
    number = 10 / 0

except:
    print("Something went wrong.")

Output:

Something went wrong.

Specific Exception Handle करना

हम general except के बजाय specific exception भी handle कर सकते हैं।

try:
    number = 10 / 0

except ZeroDivisionError:
    print("Cannot divide by zero.")

Output:

Cannot divide by zero.
Exam Tip: Specific exception को handle करना सामान्यतः अधिक स्पष्ट और useful होता है क्योंकि इससे पता चलता है कि कौन-सी समस्या handle की जा रही है।

ValueError

जब किसी value का type या format अपेक्षित operation के लिए उचित नहीं होता, तो कुछ situations में ValueError आ सकता है।

try:
    age = int("abc")

except ValueError:
    print("Invalid value.")

Output:

Invalid value.

TypeError

जब operation के लिए inappropriate types का उपयोग किया जाता है, तो TypeError हो सकता है।

try:
    result = "10" + 5

except TypeError:
    print("Invalid data types.")

Output:

Invalid data types.

NameError

जब किसी ऐसे variable या name का उपयोग किया जाता है जो defined नहीं है, तो NameError हो सकता है।

try:
    print(student_name)

except NameError:
    print("Variable is not defined.")

IndexError

जब sequence के valid range से बाहर का index access किया जाता है, तो IndexError हो सकता है।

numbers = [10, 20, 30]

try:
    print(numbers[5])

except IndexError:
    print("Index is out of range.")

KeyError

Dictionary में ऐसी key access करने पर जो मौजूद नहीं है, KeyError हो सकता है।

student = {
    "name": "Rahul"
}

try:
    print(student["age"])

except KeyError:
    print("Key not found.")

FileNotFoundError

जब ऐसी file को read करने की कोशिश की जाती है जो उपलब्ध नहीं है, तो FileNotFoundError हो सकता है।

try:
    with open("unknown.txt", "r") as file:
        data = file.read()

except FileNotFoundError:
    print("File not found.")

Multiple except Blocks

एक try block के लिए अलग-अलग exceptions को अलग-अलग except blocks से handle किया जा सकता है।

try:
    number = int(input("Enter a number: "))
    result = 10 / number
    print(result)

except ValueError:
    print("Please enter a valid number.")

except ZeroDivisionError:
    print("Number cannot be zero.")

else Block

else block तब execute होता है जब try block में कोई exception नहीं आती।

Syntax

try:
    # code

except:
    # exception

else:
    # successful execution

Example

try:
    number = 10 / 2

except ZeroDivisionError:
    print("Cannot divide by zero.")

else:
    print("Result:", number)

Output:

Result: 5.0
Exam Tip: else block तभी execute होता है जब try block successfully complete हो और exception न आए।

finally Block

finally block सामान्यतः execute होता है चाहे exception आए या न आए। इसका उपयोग cleanup जैसे कामों के लिए किया जा सकता है।

Syntax

try:
    # code

except:
    # exception

finally:
    # cleanup code

Example

try:
    number = 10 / 0

except ZeroDivisionError:
    print("Cannot divide by zero.")

finally:
    print("Program finished.")

Output:

Cannot divide by zero.
Program finished.

try + except + else + finally

try:
    number = int(input("Enter a number: "))
    result = 100 / number

except ValueError:
    print("Invalid input.")

except ZeroDivisionError:
    print("Cannot divide by zero.")

else:
    print("Result:", result)

finally:
    print("Execution completed.")

raise Statement

raise statement का उपयोग program में manually exception raise करने के लिए किया जा सकता है।

Example

age = 15

if age < 18:
    raise ValueError("Age must be 18 or above.")

यहाँ condition true होने पर ValueError manually raise किया गया है।

Exception Object

Exception को variable में store करके उसका message भी प्राप्त किया जा सकता है।

try:
    number = 10 / 0

except ZeroDivisionError as e:
    print("Error:", e)

Output:

Error: division by zero

Generic Exception Handling

कभी-कभी exception object को सामान्य तरीके से पकड़ने के लिए except Exception as e का उपयोग किया जाता है।

try:
    number = 10 / 0

except Exception as e:
    print("Error:", e)
Best Practice: जहाँ संभव हो, expected और specific exceptions को explicitly handle करें।

Exception Handling का Practical Example

try:
    marks = int(input("Enter marks: "))

    if marks < 0 or marks > 100:
        raise ValueError("Marks must be between 0 and 100.")

    print("Marks:", marks)

except ValueError as e:
    print("Error:", e)

finally:
    print("Program completed.")

File Handling के साथ Exception Handling

try:
    with open("student.txt", "r") as file:
        data = file.read()
        print(data)

except FileNotFoundError:
    print("The file was not found.")

finally:
    print("File operation completed.")

Common Python Exceptions

Exception कब हो सकती है?
ZeroDivisionError Zero से division करने पर
ValueError Invalid value होने पर
TypeError Invalid data types के operation में
NameError Undefined name/variable का उपयोग करने पर
IndexError Invalid index access करने पर
KeyError Dictionary में missing key access करने पर
FileNotFoundError Unavailable file को access करने पर
FileExistsError Existing file को x mode में create करने पर
TypeError Incompatible types के operation पर

try, except, else और finally में अंतर

Block उपयोग
try ऐसा code जिसमें exception आ सकती है
except Exception को handle करने के लिए
else Exception न आने पर execute होता है
finally Cleanup code के लिए; सामान्यतः execute होता है

Exception Handling का Flow

try block
    ↓
Exception आई?
    ↓
हाँ ──→ except block
    ↓
finally

यदि Exception नहीं आई
    ↓
else block
    ↓
finally

RBSE Class 12 Important Questions

  1. Exception Handling क्या है?
  2. Error और Exception में क्या अंतर है?
  3. Python में Exception Handling की आवश्यकता क्यों है?
  4. try block क्या है?
  5. except block क्या है?
  6. try और except का उपयोग उदाहरण सहित समझाइए।
  7. else block कब execute होता है?
  8. finally block क्या है?
  9. try, except, else और finally में अंतर लिखिए।
  10. raise statement क्या है?
  11. ZeroDivisionError क्या है?
  12. ValueError क्या है?
  13. TypeError क्या है?
  14. NameError क्या है?
  15. IndexError क्या है?
  16. KeyError क्या है?
  17. FileNotFoundError कब होता है?
  18. Multiple except blocks क्या होते हैं?
  19. Exception object क्या है?
  20. except Exception as e का उपयोग क्या है?

Frequently Asked Questions (FAQs)

Python Exception Handling क्या है?

Python Exception Handling ऐसी runtime situations को handle करने का तरीका है जिनसे program का normal execution प्रभावित हो सकता है।

try block क्या होता है?

try block में वह code लिखा जाता है जिसमें exception आने की संभावना हो सकती है।

except block का क्या उपयोग है?

except block का उपयोग try block में आने वाली exception को handle करने के लिए किया जाता है।

else block कब चलता है?

यदि try block successfully execute होता है और कोई exception नहीं आती, तो else block execute होता है।

finally block का क्या उपयोग है?

finally block का उपयोग ऐसे cleanup या final code के लिए किया जाता है जिसे सामान्यतः exception आने या न आने दोनों स्थितियों में execute करना होता है।

ZeroDivisionError कब होता है?

जब किसी number को zero से divide करने का प्रयास किया जाता है, तो ZeroDivisionError हो सकता है।

अब अगला Topic पढ़ें

RBSE Python Study Tip: Exception Handling में सबसे पहले try और except को अच्छी तरह समझें। इसके बाद else, finally और raise की practice करें। Exam में ZeroDivisionError, ValueError, TypeError, IndexError और FileNotFoundError के examples विशेष रूप से revise करें।
Official Reference:

Python Exception Handling की विस्तृत जानकारी के लिए Python की official documentation देखें।

Python Errors and Exceptions Documentation