Exception Handling: try, except, else, finally Blocks Notes in Hindi & English : एक्सेप्शन हैंडलिंग: try, except, else (सफलता पर), finally और 20 महत्वपूर्ण MCQ प्रश्न (Rajasthan IT Exam)

Post a Comment

PGDCA, BCA, B-Tech, MCA, M-Tech, B.Sc computer science राजस्थान सूचना सहायक व कंप्यूटर शिक्षक विशेष नोट्स: इस अध्याय में हम Exception Handling: try, except, else, finally Blocks (एक्सेप्शन हैंडलिंग: try, except, else (सफलता पर), finally) की संपूर्ण थ्योरी, मुख्य तकनीकी बिंदु, तुलनात्मक तालिका और विगत परीक्षाओं के पैटर्न पर आधारित 20 अति-महत्वपूर्ण बहुविकल्पीय प्रश्न (MCQs) विस्तृत हिंदी व अंग्रेजी व्याख्या सहित पढ़ेंगे।

Overview: Python structures runtime error handling using try, except, else, and finally blocks to separate normal flow from recovery and cleanup logic. Knowing exact clause execution paths, exception subclass ordering, and finally return precedence prevents silent bugs and resource leaks.

अध्याय सार: पायथन में रनटाइम त्रुटियों को संभालने के लिए try, except, else और finally ब्लॉक्स का उपयोग होता है ताकि सामान्य कोड, त्रुटि सुधार और क्लीनअप अलग रहें। इनके निष्पादन क्रम, सबक्लास ऑर्डरिंग और finally के रिटर्न नियमों को समझना बग-रहित कोड और परीक्षा के लिए अत्यंत आवश्यक है।

Exception Handling: try, except, else, finally Blocks: Detailed Notes & Architecture (एक्सेप्शन हैंडलिंग: try, except, else (सफलता पर), finally)

1. try and Targeted except Handler Matching (try और लक्षित except हैंडलर मिलान)

[EN] Code prone to runtime failures goes inside `try:`. If an exception occurs, remaining statements in `try` are immediately skipped and Python scans `except` clauses top-to-bottom using `isinstance` polymorphism. Because the first matching `except` runs exclusively, specific exception subclasses (like `ZeroDivisionError` or `FileNotFoundError`) MUST precede broader base classes (like `ArithmeticError`, `OSError`, or `Exception`). A single handler can catch multiple independent exception types using a parenthesized tuple: `except (ValueError, TypeError) as err:` (Python 3 rejects unparenthesized `except A, B:` as `SyntaxError`). Bare `except:` without a type is discouraged because it catches `KeyboardInterrupt` and `SystemExit` along with application errors.

[HI] त्रुटि उत्पन्न करने की संभावना वाला कोड `try:` में रखा जाता है। एक्सेप्शन आने पर `try` के शेष स्टेटमेंट रुक जाते हैं और ऊपर से नीचे तक मिलान करने वाला पहला `except` चलता है। पॉलीमॉर्फिज़्म के कारण विशिष्ट सबक्लास (जैसे `ZeroDivisionError`) को हमेशा सामान्य बेस क्लास (जैसे `Exception`) से पहले रखना चाहिए। एक ही ब्लॉक में कई एक्सेप्शन पकड़ने के लिए टपल सिंटैक्स `except (ValueError, TypeError) as err:` आवश्यक है (बिना कोष्ठक के `SyntaxError` आता है)। बिना नाम के खाली `except:` से बचना चाहिए क्योंकि वह `KeyboardInterrupt` (Ctrl+C) और `SystemExit` को भी पकड़ लेता है।

2. The else Clause: Strictly Success-Only Execution (else ब्लॉक: केवल पूर्ण सफलता पर निष्पादन)

[EN] An optional `else:` block placed after all `except:` clauses executes ONLY if the `try:` block finished completely with zero exceptions AND did not exit early via `return`, `break`, or `continue`. Syntax requires at least one `except` clause before `else` (`try ... else` without `except` raises `SyntaxError`). Putting non-risky continuation code inside `else:` rather than inside `try:` is a critical clean-code principle: it ensures exceptions raised by follow-up processing are NOT accidentally caught by `try`'s `except` handler. Thus, a successful run without `return` follows the path `try` -> `else` -> `finally`.

[HI] सभी `except:` ब्लॉक्स के बाद लिखा गया `else:` ब्लॉक केवल तभी चलता है जब `try:` ब्लॉक बिना किसी एक्सेप्शन के और बिना `return`/`break` के पूरा समाप्त हो जाए। नियम के अनुसार `else:` से पहले कम से कम एक `except:` होना अनिवार्य है, अन्यथा `SyntaxError` आता है। आगे की सुरक्षित प्रक्रिया को `try:` के बजाय `else:` में रखने से बाद के कोड में आने वाली अप्रत्याशित त्रुटियां गलती से `try` के `except` में नहीं फंसतीं। अतः बिना त्रुटि वाले निष्पादन का क्रम `try` -> `else` -> `finally` होता है।

3. The finally Clause: Guaranteed Cleanup & return Precedence (finally ब्लॉक: अनिवार्य क्लीनअप और return प्राथमिकता)

[EN] The `finally:` clause ALWAYS executes before control leaves the `try` construct—whether `try` succeeded, an `except` caught an error, an unhandled exception is propagating upward, or `try`/`except`/`else` executed `return`, `break`, or `continue`. A `try` statement can pair directly with `finally:` without any `except` (`try: ... finally: ...`) purely to ensure resource cleanup like closing sockets or locks. Crucial exam trap: if `finally:` itself executes a `return` (or `break`) or raises a new exception, it silently OVERRIDES and discards any pending `return` value or active unhandled exception from `try`/`except`!

[HI] `finally:` ब्लॉक हर परिस्थिति में चलता ही चलता है—चाहे `try` सफल हो, `except` चले, अनहैंडल्ड एक्सेप्शन बाहर जा रहा हो, या अंदर `return`/`break` आ गया हो। बिना `except` के भी `try: ... finally: ...` लिखना पूर्णतः वैध सिंटैक्स है, जिसका उपयोग लॉक या कनेक्शन मुक्त करने में होता है। परीक्षा का प्रमुख प्रश्न: यदि `finally:` के भीतर स्वयं `return` लिखा हो, तो वह `try` या `except` के पिछले `return` मान या लंबित एक्सेप्शन को दबाकर अपना नया मान लौटा देता है।

4. Re-Raising Exceptions and Explicit Chaining (raise ... from) (एक्सेप्शन री-रेज़ करना और एक्सप्लिसिट चेनिंग (raise ... from))

[EN] Executing a bare `raise` statement with no arguments inside an `except` block re-raises the exact currently active exception while preserving its original stack traceback. This pattern is ideal for logging an error locally before passing responsibility to the caller. To translate a low-level error into a domain-specific exception without losing root-cause history, use `raise ServiceError('DB failed') from orig_err`, which sets `__cause__` on the new exception. Using `raise ServiceError(...) from None` suppresses the noisy prior exception context when presenting clean user errors.

[HI] `except` ब्लॉक के भीतर बिना आर्ग्यूमेंट के केवल `raise` लिखने पर वही मूल एक्सेप्शन अपने वास्तविक ट्रेसबैक सहित ऊपरी कॉलर को पुनः भेज दिया जाता है। लॉगिंग करने के बाद त्रुटि को आगे बढ़ाने के लिए यह तरीका सर्वोत्तम है। यदि आप किसी निम्न-स्तरीय त्रुटि को नई कस्टम त्रुटि में बदलना चाहते हैं और मूल कारण भी सुरक्षित रखना चाहते हैं, तो `raise ServiceError('fail') from orig_err` उपयोग करें जो `__cause__` सेट करता है। अनावश्यक पिछला संदर्भ छिपाने के लिए `from None` का उपयोग किया जाता है।

Syntax, Formula & Technical Example (Exception Handling: try, except, else, finally Blocks)

def safe_divide(a, b):
    try:
        res = int(a) / int(b)
    except (ValueError, ZeroDivisionError) as e:
        print("Handled error:", type(e).__name__); return None
    else:
        print("Division succeeded"); return res
    finally:
        print("Cleanup always runs")
print("Result:", safe_divide("10", "2"))

Exception Handling: try, except, else, finally Blocks Quick Reference & Comparison Table

Block ClauseWhen It ExecutesKey Exam Fact
tryAlways entered firstKeep minimal risky statements inside to avoid masking bugs
except Ex as eOnly on matching exception in tryPut specific subclasses before Exception; tuple for multi-catch
elseOnly if try finishes with 0 exceptionsSkipped on exception or return; requires at least one except
finallyAlways runs unconditionallyRuns even after return; finally's own return overrides all

Exception Handling: try, except, else, finally Blocks Top 20 Bilingual MCQs with Answers

Q1. In a `try-except-else-finally` construct where NO exception occurs and no `return` is inside `try`, what is the exact execution order?

(`try-except-else-finally` ब्लॉक में यदि कोई एक्सेप्शन न आए और `try` में `return` न हो, तो निष्पादन क्रम क्या होगा?)

(A) try -> else -> finally

(B) try -> except -> else -> finally

(C) try -> finally -> else

(D) try -> finally only

Correct Answer: (A)

[EN] When `try` succeeds cleanly, `except` is skipped, `else` runs next, and `finally` executes last.

[HI] `try` के सफल होने पर `except` छूट जाता है, फिर `else` चलता है और अंत में `finally` चलता है।

Q2. When an exception raised inside `try` is caught by an `except` block, which blocks execute?

(जब `try` में आया एक्सेप्शन `except` द्वारा पकड़ लिया जाता है, तो कौन-कौन से ब्लॉक चलते हैं?)

(A) try -> else -> finally

(B) try (until error) -> matching except -> finally

(C) try -> except only (finally is skipped)

(D) try -> except -> else -> finally

Correct Answer: (B)

[EN] Once an exception enters `except`, `else` is skipped, and `finally` still runs unconditionally.

[HI] एक्सेप्शन आने पर `except` चलने के बाद `else` नहीं चलता, लेकिन `finally` अवश्य चलता है।

Q3. What happens if a `try` block contains `return 10` and its `finally` block contains `return 20`?

(यदि `try` ब्लॉक में `return 10` और `finally` ब्लॉक में `return 20` लिखा हो, तो फंक्शन क्या लौटाएगा?)

(A) None

(B) 10

(C) 20

(D) SyntaxError

Correct Answer: (C)

[EN] A `return` inside `finally` always executes last and overrides any pending `return` (or active exception) from `try` or `except`.

[HI] `finally` का `return` हमेशा पिछले किसी भी `return` मान या लंबित एक्सेप्शन को ओवरराइड कर देता है, इसलिए 20 लौटेगा।

Q4. What happens if `try:` executes `return 10` and `finally:` executes `print('F')` without a `return`?

(यदि `try:` में `return 10` हो और `finally:` में बिना `return` के केवल `print('F')` हो, तो क्या होगा?)

(A) It runs else and then returns 10

(B) It prints 'F' first, skips else, and then returns 10

(C) It prints 'F' and returns None

(D) It returns 10 immediately and never prints 'F'

Correct Answer: (B)

[EN] `finally` runs right before the function actually returns 10, while `else` is skipped because `try` jumped out via `return`.

[HI] `finally` फंक्शन से बाहर निकलने से ठीक पहले `'F'` प्रिंट करता है और फिर `10` लौटता है (`else` छूट जाता है)।

Q5. Which base class sits at the very root of ALL Python exceptions including `KeyboardInterrupt` and `SystemExit`?

(`KeyboardInterrupt` और `SystemExit` सहित सभी पायथन एक्सेप्शन्स के शीर्ष पर कौन-सी बेस क्लास होती है?)

(A) Exception

(B) StandardError

(C) Error

(D) BaseException

Correct Answer: (D)

[EN] `BaseException` is the root class; `Exception` inherits from `BaseException`, whereas `KeyboardInterrupt` and `SystemExit` inherit directly from `BaseException`.

[HI] `BaseException` सभी एक्सेप्शन्स की मूल (root) क्लास है; `KeyboardInterrupt` व `SystemExit` सीधे इससे इनहेरिट करते हैं।

Q6. Why does PEP 8 recommend `except Exception:` instead of a bare `except:`?

(PEP 8 खाली `except:` के बजाय `except Exception:` लिखने की सलाह क्यों देता है?)

(A) Bare except: cannot catch ValueError or TypeError

(B) Bare except: is a SyntaxError in Python 3

(C) Bare except: traps KeyboardInterrupt (Ctrl+C) and SystemExit, making programs hard to terminate

(D) except Exception: runs 10x faster at runtime

Correct Answer: (C)

[EN] Catching `Exception` avoids accidentally swallowing `SystemExit`, `KeyboardInterrupt`, and `GeneratorExit`.

[HI] `except Exception:` लिखने से Ctrl+C (`KeyboardInterrupt`) और `sys.exit()` (`SystemExit`) गलती से ब्लॉक नहीं होते।

Q7. What happens if you place `except Exception:` ABOVE `except ZeroDivisionError:`?

(यदि आप `except Exception:` को `except ZeroDivisionError:` के ऊपर लिख दें तो क्या होगा?)

(A) Python automatically reorders them by specificity

(B) SyntaxError at compile time

(C) ZeroDivisionError is caught by the first except Exception: block, making the second block unreachable

(D) ZeroDivisionError skips Exception and matches the second block

Correct Answer: (C)

[EN] Handlers match top-to-bottom via subclass checks; because `ZeroDivisionError` is an `Exception`, the broader handler intercepts it first.

[HI] हैंडलर ऊपर से नीचे जांचे जाते हैं, इसलिए `Exception` पहले ही `ZeroDivisionError` को पकड़ लेगा और नीचे वाला ब्लॉक कभी नहीं चलेगा।

Q8. What is the valid Python 3 syntax to catch both `ValueError` and `TypeError` in one `except` clause and bind it to `e`?

(पायथन 3 में एक ही `except` ब्लॉक में `ValueError` और `TypeError` दोनों को `e` नाम से पकड़ने का सही सिंटैक्स क्या है?)

(A) except ValueError or TypeError as e:

(B) except [ValueError, TypeError], e:

(C) except (ValueError, TypeError) as e:

(D) except ValueError, TypeError as e:

Correct Answer: (C)

[EN] Python 3 mandates parentheses around multiple exception types and uses `as` for binding the exception instance.

[HI] पायथन 3 में कई एक्सेप्शन्स को कोष्ठक में टपल बनाकर `as e` के साथ लिखना अनिवार्य है।

Q9. Which of the following `try` block combinations is a `SyntaxError` in Python?

(पायथन में `try` ब्लॉक का निम्न में से कौन-सा संयोजन `SyntaxError` देता है?)

(A) try ... except ... else

(B) try ... finally (with no except block)

(C) try ... else (with no except block)

(D) try ... except ... finally

Correct Answer: (C)

[EN] An `else` clause is strictly tied to `except` clauses and is syntactically invalid without at least one `except`.

[HI] `else` ब्लॉक बिना कम से कम एक `except` के नहीं लिखा जा सकता; जबकि `try ... finally` वैध है।

Q10. What happens when a `try` block raises `KeyError`, there is only `except ValueError:`, and a `finally:` block exists?

(यदि `try` में `KeyError` आए, केवल `except ValueError:` मौजूद हो, और साथ में `finally:` भी हो, तो क्या होगा?)

(A) finally runs first, and then the unhandled KeyError propagates upward

(B) KeyError crashes immediately without running finally

(C) finally suppresses KeyError silently

(D) except ValueError catches KeyError anyway

Correct Answer: (A)

[EN] Even when an exception finds no matching `except` handler, Python executes `finally` before propagating the exception to callers.

[HI] यदि कोई मैचिंग `except` न मिले तब भी `finally` पहले चलेगा और उसके बाद `KeyError` ऊपर कॉलर तक जाएगा।

Q11. Inside an `except ValueError:` block, what does writing bare `raise` with no expression do?

(`except ValueError:` ब्लॉक के अंदर बिना किसी नाम के केवल `raise` लिखने से क्या होता है?)

(A) Ignores the exception and continues

(B) SyntaxError: raise requires an exception class

(C) Re-raises the active ValueError along with its original traceback

(D) Raises a generic RuntimeError

Correct Answer: (C)

[EN] A bare `raise` re-throws the currently handled exception untouched so its original traceback lines remain intact.

[HI] खाली `raise` वर्तमान में पकड़े गए एक्सेप्शन को उसके मूल ट्रेसबैक के साथ आगे भेज देता है।

Q12. What attribute is set on the new exception when you execute `raise RuntimeError('fail') from err`?

(`raise RuntimeError('fail') from err` चलाने पर नए एक्सेप्शन ऑब्जेक्ट पर कौन-सा एट्रिब्यूट सेट होता है?)

(A) __cause__

(B) __origin__

(C) __base__

(D) __parent__

Correct Answer: (A)

[EN] Explicit exception chaining (`raise A from B`) assigns `B` to `A.__cause__`.

[HI] `raise ... from err` द्वारा नए एक्सेप्शन में `__cause__` एट्रिब्यूट पर `err` सेट हो जाता है।

Q13. What is the output of: try: x = 10 // 2 except ZeroDivisionError: print('E', end='') else: print('OK', end='') finally: print('F', end='')

(कोड का आउटपुट क्या होगा: try: x = 10 // 2 except ZeroDivisionError: print('E', end='') else: print('OK', end='') finally: print('F', end=''))

(A) OKF

(B) EF

(C) OK

(D) EOKF

Correct Answer: (A)

[EN] `10 // 2` succeeds cleanly, skipping `except`, printing `'OK'` in `else`, and `'F'` in `finally`.

[HI] `10 // 2` बिना त्रुटि के चलता है, इसलिए `else` से `'OK'` और `finally` से `'F'` प्रिंट होकर `OKF` बनता है।

Q14. What is the output of: try: x = int('hi') except ValueError: print('V', end='') except Exception: print('E', end='') finally: print('F', end='')

(कोड का आउटपुट क्या होगा: try: x = int('hi') except ValueError: print('V', end='') except Exception: print('E', end='') finally: print('F', end=''))

(A) EF

(B) VEF

(C) VF

(D) V

Correct Answer: (C)

[EN] Only the first matching `except` (`ValueError`) runs—not both—followed by `finally`, printing `'VF'`.

[HI] केवल पहला मेल खाने वाला `except ValueError` चलता है (`Exception` नहीं चलता), और फिर `finally` से `'VF'` प्रिंट होता है।

Q15. Where does `else:` get placed relative to `except:` and `finally:` in a `try` statement?

(`try` स्टेटमेंट में `else:` ब्लॉक को `except:` और `finally:` के सापेक्ष किस स्थान पर लिखा जाता है?)

(A) After all except blocks and strictly before finally

(B) Before all except blocks

(C) After the finally block

(D) Inside the finally block

Correct Answer: (A)

[EN] Python's strict grammar order is `try -> except -> else -> finally`.

[HI] पायथन सिंटैक्स में सटीक क्रम `try -> except -> else -> finally` ही मान्य है।

Q16. Which statement is NOT true about Python `try`, `except`, `else`, and `finally`?

(पायथन के `try`, `except`, `else` और `finally` के बारे में निम्न में से कौन-सा कथन सत्य नहीं है?)

(A) The else block executes regardless of whether an exception was caught or not

(B) finally runs even when try executes a return statement

(C) Multiple except blocks can follow a single try block

(D) A try block can have a finally block without any except block

Correct Answer: (A)

[EN] `else` runs ONLY if NO exception was raised in `try`; if an exception was caught by `except`, `else` is skipped.

[HI] `else` ब्लॉक केवल तभी चलता है जब `try` में कोई एक्सेप्शन न आया हो; `except` चलने पर `else` नहीं चलता।

Q17. Within Exception Handling: try, except, else, finally Blocks, which block clause directly maps to: "Always entered first"?

(Exception Handling: try, except, else, finally Blocks में कौन सा Block Clause सीधे "Always entered first" से संबंधित है?)

(A) try

(B) except Ex as e

(C) else

(D) finally

Correct Answer: (A)

[EN] In Exception Handling: try, except, else, finally Blocks, 'try' handles 'Always entered first' (Keep minimal risky statements inside to avoid masking bugs).

[HI] Exception Handling: try, except, else, finally Blocks में 'try' का कार्य/विवरण 'Always entered first' (Keep minimal risky statements inside to avoid masking bugs) है।

Q18. Which option accurately describes 'except Ex as e' in Exception Handling: try, except, else, finally Blocks?

(Exception Handling: try, except, else, finally Blocks के संदर्भ में 'except Ex as e' की सही विशेषता कौन सी है?)

(A) Only on matching exception in try

(B) Always entered first

(C) Always runs unconditionally

(D) Only if try finishes with 0 exceptions

Correct Answer: (A)

[EN] 'except Ex as e' provides 'Only on matching exception in try' — key point: Put specific subclasses before Exception; tuple for multi-catch.

[HI] 'except Ex as e' का मुख्य विवरण 'Only on matching exception in try' है (Put specific subclasses before Exception; tuple for multi-catch)।

Q19. In Exception Handling: try, except, else, finally Blocks, identify the correct parameter for the specification: "Only if try finishes with 0 exceptions".

(Exception Handling: try, except, else, finally Blocks में "Only if try finishes with 0 exceptions" विवरण किस विकल्प के लिए सही है?)

(A) except Ex as e

(B) finally

(C) try

(D) else

Correct Answer: (D)

[EN] 'else' corresponds to 'Only if try finishes with 0 exceptions' (Skipped on exception or return; requires at least one except).

[HI] 'else' का संबंध 'Only if try finishes with 0 exceptions' (Skipped on exception or return; requires at least one except) से है।

Q20. Considering Exception Handling: try, except, else, finally Blocks, what key behavior defines 'finally'?

(Exception Handling: try, except, else, finally Blocks में 'finally' की मुख्य भूमिका या मान क्या है?)

(A) Always runs unconditionally

(B) Only if try finishes with 0 exceptions

(C) Always entered first

(D) Only on matching exception in try

Correct Answer: (A)

[EN] 'finally' represents 'Always runs unconditionally' (Runs even after return; finally's own return overrides all).

[HI] 'finally' का अर्थ/मान 'Always runs unconditionally' है (Runs even after return; finally's own return overrides all)।

Exception Handling: try, except, else, finally Blocks — Exam FAQs

Q1: Why should continuation code be placed in `else:` instead of inside the `try:` block?

आगे के सामान्य कोड को `try:` के अंदर लिखने के बजाय `else:` में क्यों रखना चाहिए?

[EN] Placing extra code inside `try:` widens the protected zone, meaning an unexpected bug in that follow-up code (such as a ValueError or KeyError) could get silently caught by the `except` meant only for the original risky line. `else:` keeps error catching surgical and narrow.

[HI] `try:` के अंदर बहुत सारा कोड रखने पर यदि बाद वाले सामान्य कोड में भी वैसा ही एक्सेप्शन आ जाए, तो वह अनजाने में पुराने `except` में पकड़ा जाएगा। `else:` केवल सफलता के बाद चलता है और त्रुटि पहचान को सटीक रखता है।

Q2: Does Python execute `finally` if an unhandled exception crashes the program?

यदि कोई अनहैंडल्ड एक्सेप्शन प्रोग्राम को क्रैश कर दे, तो क्या `finally` तब भी चलता है?

[EN] Yes. Before printing the traceback and terminating (or propagating upward to an outer handler), Python unwinds the stack and executes the `finally` block so open resources or locks are cleanly released.

[HI] हां, प्रोग्राम क्रैश होने या ट्रेसबैक दिखने से पहले पायथन `finally` ब्लॉक को अवश्य चलाता है ताकि खुले रिसोर्स या फाइलें सुरक्षित बंद हो सकें।

Q3: What happens if an exception occurs inside the `finally` block itself?

यदि स्वयं `finally` ब्लॉक के भीतर ही कोई नया एक्सेप्शन आ जाए तो क्या होता है?

[EN] The new exception raised inside `finally` replaces any previously active exception (attaching the old one to `__context__`) or discards any pending `return` value from `try`/`except`.

[HI] `finally` में आया नया एक्सेप्शन पिछले लंबित एक्सेप्शन या `return` मान को प्रतिस्थापित कर देता है और खुद बाहर प्रोपेगेट होता है।

Related Posts

  • Loading related posts...

Post a Comment

Search Topic Notes & 20 MCQs (Hindi / English)