← Back to Python Course | Chapter 10: Exception Handling | Lesson 2 of 5

Python try-except

try-except एक safety net जैसा है: आप कोई risky काम try करते हैं, और अगर वह fail हो जाए तो आप समस्या पकड़कर कुछ समझदारी भरा करते हैं। इस तरह program crash नहीं होता।
Syntax
python
try:
    # risky code
except ExceptionType as error:
    # handle error
except (TypeA, TypeB):
    # handle either

try-except Block

try block के अंदर का code पहले चलता है, और अगर उसमें कोई statement कोई exception raise करता है, तो execution आगे बढ़ने की बजाय तुरंत matching except block पर चला जाता है -- अगर कोई exception नहीं होता, तो except block को बस पूरी तरह skip कर दिया जाता है।

उदाहरण: The try-except Block

python
try:
    print(10 / 2)  # no exception raised here
except ZeroDivisionError:
    print("This does not run")

कई Exceptions Handle करना

कई except clauses लिखना आपको अलग-अलग error types को अलग-अलग तरह से handle करने देता है (missing file और bad data को अलग-अलग fixes चाहिए), या जब उन्हें एक ही तरह handle किया जाना हो तो आप संबंधित exception types को एक ही except (ValueError, TypeError): block में group कर सकते हैं।

उदाहरण: Handling Multiple Exceptions

python
try:
    int("abc")
except (ValueError, TypeError):  # handles either exception type the same way
    print("Caught ValueError or TypeError")

Exception को Variable के रूप में Catch करना

'except ValueError as e:' exception object को एक variable में save करता है ताकि आप str(e) से उसका असली message देख सकें, जो 'कहीं ValueError हुआ' जानने से कहीं ज़्यादा logging या debugging के लिए उपयोगी है।

उदाहरण: Catching Exception as Variable

python
try:
    int("abc")
except ValueError as e:  # saves the exception object for inspection
    print(str(e))

Nested try-except Blocks

एक try/except को दूसरे try/except के अंदर रखना आपको fallback recovery action try करने देता है और उस recovery में होने वाली विफलताओं को भी catch करने देता है -- यह 'primary server try करो, और अगर उस तक पहुँचना fail हो तो backup server try करो, और उसकी विफलता भी handle करो' जैसी चीज़ों के लिए उपयोगी है।

उदाहरण: Nested try-except Blocks

python
try:
    try:
        raise ConnectionError("primary server down")
    except ConnectionError:
        raise ConnectionError("backup server also down")  # failure of the fallback itself
except ConnectionError as e:
    print(e)

Bare except से बचना

बिना किसी exception type वाला bare 'except:' literally सब कुछ catch कर लेता है, जिसमें KeyboardInterrupt जैसी चीज़ें भी शामिल हैं जिन्हें कोई user program रोकने के लिए जानबूझकर trigger कर सकता है -- इसकी बजाय 'except Exception:' catch करना सामान्य errors तो catch करता है पर उन system-level signals को गुज़रने देता है।

उदाहरण: Avoiding Bare except

python
try:
    int("abc")
except Exception as e:  # catches ordinary errors but lets KeyboardInterrupt through
    print("Caught ordinary errors, not KeyboardInterrupt:", e)
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
🔒

Chapter Quiz — Complete all 5 topics to unlock

0/5 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.