Raising Exceptions (raise) and Custom User-Defined Exceptions Notes in Hindi & English : एक्सेप्शन उठाना (raise) और कस्टम एक्सेप्शन क्लास निर्माण और 20 महत्वपूर्ण MCQ प्रश्न (Rajasthan IT Exam)

Post a Comment

PGDCA, BCA, B-Tech, MCA, M-Tech, B.Sc computer science राजस्थान सूचना सहायक व कंप्यूटर शिक्षक विशेष नोट्स: इस अध्याय में हम Raising Exceptions (raise) and Custom User-Defined Exceptions (एक्सेप्शन उठाना (raise) और कस्टम एक्सेप्शन क्लास निर्माण) की संपूर्ण थ्योरी, मुख्य तकनीकी बिंदु, तुलनात्मक तालिका और विगत परीक्षाओं के पैटर्न पर आधारित 20 अति-महत्वपूर्ण बहुविकल्पीय प्रश्न (MCQs) विस्तृत हिंदी व अंग्रेजी व्याख्या सहित पढ़ेंगे।

Overview: The raise statement in Python explicitly triggers a built-in or user-defined exception when a runtime invariant or domain rule is violated. Custom exceptions are created by subclassing Exception so callers can isolate and handle application-specific failures cleanly.

अध्याय सार: पायथन में raise स्टेटमेंट का उपयोग रनटाइम नियम या बिजनेस लॉजिक भंग होने पर जानबूझकर बिल्ट-इन या कस्टम एक्सेप्शन उत्पन्न करने के लिए किया जाता है। कस्टम एक्सेप्शन बनाने के लिए Exception क्लास को इनहेरिट किया जाता है जिससे प्रोग्राम विशिष्ट त्रुटियों को स्पष्ट रूप से हैंडल कर सके।

Raising Exceptions (raise) and Custom User-Defined Exceptions: Detailed Notes & Architecture (एक्सेप्शन उठाना (raise) और कस्टम एक्सेप्शन क्लास निर्माण)

1. Syntax and Semantics of the raise Statement (raise स्टेटमेंट का सिंटैक्स और कार्यप्रणाली)

[EN] The raise keyword accepts either an exception instance such as raise ValueError('Invalid age') or an exception class such as raise ValueError, which Python instantiates with zero arguments. Inside an except handler, a bare raise statement re-throws the currently active exception while preserving its original stack traceback. Python 3 also supports explicit exception chaining via raise NewError('msg') from orig_err (setting __cause__) and suppression of implicit context via from None.

[HI] raise कीवर्ड या तो किसी एक्सेप्शन इंस्टेंस जैसे raise ValueError('Invalid age') या केवल क्लास जैसे raise ValueError को स्वीकार करता है जिसे पायथन स्वतः बिना आर्ग्यूमेंट के इंस्टैंशिएट करता है। except ब्लॉक के भीतर बिना किसी आर्ग्यूमेंट के केवल raise लिखने पर वही सक्रिय एक्सेप्शन मूल ट्रेसबैक के साथ पुनः ऊपर भेजा जाता है। पायथन 3 में raise NewError() from orig_err से __cause__ द्वारा एक्सप्लिसिट चेनिंग और from None से पिछले कॉन्टेक्स्ट को छिपाने की सुविधा मिलती है।

2. Designing Custom User-Defined Exception Classes (कस्टम यूजर-डिफाइंड एक्सेप्शन क्लास का निर्माण)

[EN] User-defined exceptions must inherit directly or indirectly from Exception rather than BaseException so that standard except Exception blocks catch them without accidentally swallowing SystemExit or KeyboardInterrupt. Following PEP 8, custom exception names end with the Error suffix, such as InsufficientFundsError. Overriding __init__ lets developers attach structured metadata like error_code or account_id while calling super().__init__(message) to populate the standard args tuple.

[HI] यूजर-डिफाइंड एक्सेप्शन को BaseException के बजाय हमेशा Exception क्लास से इनहेरिट करना चाहिए, ताकि सामान्य except Exception ब्लॉक उन्हें पकड़ सकें और SystemExit या KeyboardInterrupt अनजाने में न दबें। PEP 8 के अनुसार कस्टम एक्सेप्शन के नाम के अंत में Error प्रत्यय (जैसे InsufficientFundsError) लगाना उचित माना जाता है। __init__ को ओवरराइड करके error_code या balance जैसे अतिरिक्त एट्रिब्यूट्स जोड़े जा सकते हैं, जबकि super().__init__(message) बेस args टपल को सेट करता है।

3. Exception Hierarchy and the assert Statement (एक्सेप्शन पदानुक्रम और assert स्टेटमेंट)

[EN] Python's exception tree is rooted at BaseException, which splits into SystemExit, KeyboardInterrupt, GeneratorExit, and Exception; common errors like ArithmeticError, LookupError, ValueError, and OSError all descend from Exception. Trying to raise an object that does not derive from BaseException triggers a TypeError. Meanwhile, assert cond, msg compiles to raising AssertionError when __debug__ is True, meaning assertions are completely stripped when running python -O and must never replace raise for input validation.

[HI] पायथन का एक्सेप्शन ट्री BaseException से शुरू होता है, जो SystemExit, KeyboardInterrupt, GeneratorExit और Exception में बंटता है; ArithmeticError, LookupError, ValueError और OSError सभी Exception के अधीन आते हैं। यदि कोई ऐसा ऑब्जेक्ट raise किया जाए जो BaseException का सबक्लास न हो, तो TypeError आता है। दूसरी ओर, assert स्टेटमेंट केवल __debug__ सक्रिय रहने पर AssertionError उठाता है और python -O मोड में हटा दिया जाता है, इसलिए यूजर इनपुट जांचने के लिए assert की जगह raise का ही उपयोग करना चाहिए।

4. Stack Unwinding and Chaining Best Practices (स्टैक अनवाइंडिंग और एक्सेप्शन चेनिंग नियम)

[EN] When raise executes, normal control flow aborts immediately and Python unwinds the call stack frame by frame until a matching except clause intercepts the exception or sys.excepthook terminates the script. If a new exception occurs inside an except block without 'from', Python sets __context__ automatically to record both errors. Defining a common package base class like AppError(Exception) with specialized subclasses allows API consumers to handle broad or granular failures predictably.

[HI] जैसे ही raise निष्पादित होता है, सामान्य फ्लो रुक जाता है और पायथन कॉल स्टैक के प्रत्येक फ्रेम को तब तक वापस खोलता (unwind) है जब तक उपयुक्त except ब्लॉक न मिल जाए या sys.excepthook प्रोग्राम को रोक न दे। यदि except ब्लॉक के भीतर बिना 'from' के नया एक्सेप्शन उठता है, तो पायथन स्वतः __context__ सेट कर देता है। बड़े प्रोजेक्ट में AppError(Exception) जैसी एक बेस क्लास बनाकर उससे विशिष्ट चाइल्ड एक्सेप्शन निकालना बेहतर मॉड्यूलर त्रुटि प्रबंधन प्रदान करता है।

Syntax, Formula & Technical Example (Raising Exceptions (raise) and Custom User-Defined Exceptions)

class BalanceError(Exception):
    def __init__(self, balance, amount):
        self.balance, self.amount = balance, amount
        super().__init__(f'Short by {amount - balance}')

def withdraw(balance, amount):
    if amount > balance:
        raise BalanceError(balance, amount)
    return balance - amount

Raising Exceptions (raise) and Custom User-Defined Exceptions Quick Reference & Comparison Table

Construct / ClassTechnical MechanismExam Key Point
raise Exc('msg')Throws a new exception instance immediatelyUnwinds stack to nearest matching except
bare raiseRe-throws active exception inside except blockPreserves original traceback without reset
raise A from BChains explicit cause in A.__cause__Using from None sets __suppress_context__
class MyError(Exception)Defines custom application exception classAvoid inheriting directly from BaseException

Raising Exceptions (raise) and Custom User-Defined Exceptions Top 20 Bilingual MCQs with Answers

Q1. Which base class should custom user-defined exception classes inherit from in Python?

(पायथन में कस्टम यूजर-डिफाइंड एक्सेप्शन क्लास को किस बेस क्लास से इनहेरिट करना चाहिए?)

(A) Exception

(B) ErrorObject

(C) RuntimeWarning

(D) BaseException

Correct Answer: (A)

[EN] User-defined exceptions should subclass Exception so KeyboardInterrupt and SystemExit are not accidentally caught by except Exception.

[HI] कस्टम एक्सेप्शन को Exception से इनहेरिट करना चाहिए ताकि except Exception द्वारा KeyboardInterrupt या SystemExit अनजाने में न पकड़े जाएं।

Q2. What happens if you execute raise 'Invalid input' in Python 3?

(पायथन 3 में raise 'Invalid input' चलाने पर क्या होगा?)

(A) Invalid input is printed without stopping

(B) A generic StringError is raised

(C) SyntaxError occurs at compile time

(D) TypeError is raised because strings do not inherit from BaseException

Correct Answer: (D)

[EN] Python requires all raised objects to be instances or subclasses of BaseException; raising a str raises TypeError.

[HI] पायथन में केवल BaseException के इंस्टेंस या सबक्लास को ही raise किया जा सकता है; str उठाने पर TypeError आता है।

Q3. What is the effect of writing a bare raise statement inside an except block?

(except ब्लॉक के भीतर बिना आर्ग्यूमेंट के केवल raise लिखने का क्या प्रभाव होता है?)

(A) It re-raises the active exception while preserving its original traceback

(B) It raises RuntimeError because no class was specified

(C) It ignores the error and continues the try block

(D) It clears the traceback and converts the error to Warning

Correct Answer: (A)

[EN] A bare raise inside an except handler re-throws the currently handled exception with its exact original stack frames intact.

[HI] except ब्लॉक के अंदर अकेला raise वर्तमान सक्रिय एक्सेप्शन को उसके मूल ट्रेसबैक के साथ पुनः ऊपर भेजता है।

Q4. Which attribute stores the explicit cause set by raise NewErr() from orig_err?

(raise NewErr() from orig_err द्वारा सेट किया गया स्पष्ट कारण किस एट्रिब्यूट में संग्रहीत होता है?)

(A) __cause__

(B) __parent__

(C) __reason__

(D) __origin__

Correct Answer: (A)

[EN] Explicit exception chaining with 'from' assigns orig_err to NewErr.__cause__ and sets __suppress_context__ to True.

[HI] 'from' कीवर्ड से की गई एक्सप्लिसिट चेनिंग मूल एक्सेप्शन को __cause__ एट्रिब्यूट में सहेजती है।

Q5. What does raise CustomError('Failed') from None accomplish?

(raise CustomError('Failed') from None लिखने का क्या उद्देश्य है?)

(A) It returns None instead of throwing an error

(B) It prevents CustomError from being caught by try-except

(C) It suppresses display of the previous exception context in the traceback

(D) It converts CustomError into an AssertionError

Correct Answer: (C)

[EN] Using 'from None' sets __suppress_context__ = True so internal implementation exceptions are hidden from the formatted traceback.

[HI] 'from None' का उपयोग __suppress_context__ को True करता है जिससे पिछला आंतरिक एक्सेप्शन ट्रेसबैक में प्रदर्शित नहीं होता।

Q6. Which of the following built-in exceptions does NOT inherit from Exception?

(निम्नलिखित में से कौन-सा बिल्ट-इन एक्सेप्शन Exception क्लास से इनहेरिट नहीं होता?)

(A) ZeroDivisionError

(B) ValueError

(C) KeyboardInterrupt

(D) KeyError

Correct Answer: (C)

[EN] KeyboardInterrupt, SystemExit, and GeneratorExit inherit directly from BaseException, not Exception.

[HI] KeyboardInterrupt, SystemExit और GeneratorExit सीधे BaseException से इनहेरिट होते हैं, Exception से नहीं।

Q7. What happens to assert statements when a Python script is executed with python -O?

(जब पायथन स्क्रिप्ट को python -O फ्लैग के साथ चलाया जाता है तो assert स्टेटमेंट का क्या होता है?)

(A) They are ignored and stripped from the compiled bytecode

(B) They raise ValueError instead of AssertionError

(C) They automatically log warnings to stderr

(D) They run twice for strict verification

Correct Answer: (A)

[EN] The -O optimization flag sets __debug__ to False and removes assert nodes from compiled bytecode.

[HI] -O ऑप्टिमाइजेशन फ्लैग __debug__ को False कर देता है और बाइटकोड से सभी assert स्टेटमेंट हटा देता है।

Q8. In Python's exception hierarchy, ZeroDivisionError is a direct subclass of which class?

(पायथन के एक्सेप्शन पदानुक्रम में ZeroDivisionError किस क्लास का सीधा सबक्लास है?)

(A) ArithmeticError

(B) ValueError

(C) MathWarning

(D) LookupError

Correct Answer: (A)

[EN] ArithmeticError is the base class for ZeroDivisionError, OverflowError, and FloatingPointError.

[HI] ArithmeticError वह बेस क्लास है जिससे ZeroDivisionError, OverflowError और FloatingPointError निकलते हैं।

Q9. Both IndexError and KeyError share which immediate parent exception class?

(IndexError और KeyError दोनों किस एकसमान पेरेंट एक्सेप्शन क्लास को साझा करते हैं?)

(A) TypeError

(B) LookupError

(C) AttributeError

(D) NameError

Correct Answer: (B)

[EN] LookupError is the common parent for sequence/mapping lookup failures: IndexError and KeyError.

[HI] LookupError वह साझा पेरेंट क्लास है जिसके अंतर्गत IndexError और KeyError दोनों आते हैं।

Q10. According to PEP 8, what naming suffix is recommended for custom exception classes?

(PEP 8 मानक के अनुसार कस्टम एक्सेप्शन क्लास के नाम के अंत में कौन-सा प्रत्यय (suffix) सुझाया गया है?)

(A) Error

(B) Throw

(C) ExceptionBase

(D) Fault

Correct Answer: (A)

[EN] PEP 8 advises ending custom exception names with 'Error' (e.g., AuthError) when they represent error conditions.

[HI] PEP 8 के अनुसार त्रुटि दर्शाने वाली कस्टम एक्सेप्शन क्लास के नाम के अंत में 'Error' (जैसे AuthError) होना चाहिए।

Q11. Why should a custom exception constructor call super().__init__(message)?

(कस्टम एक्सेप्शन के कंस्ट्रक्टर में super().__init__(message) कॉल करना क्यों आवश्यक है?)

(A) To register the class inside sys.modules

(B) To initialize the inherited args tuple and standard string representation

(C) To force Garbage Collection immediately

(D) To bypass stack unwinding during raise

Correct Answer: (B)

[EN] Calling super().__init__(message) populates self.args so str(exc) and traceback printers show the message cleanly.

[HI] super().__init__(message) कॉल करने से self.args सही ढंग से सेट होता है और str(exc) तथा ट्रेसबैक संदेश दिखता है।

Q12. What happens in Python when raise ValueError is written without parentheses?

(यदि पायथन में बिना कोष्ठक (parentheses) के raise ValueError लिखा जाए तो क्या होता है?)

(A) Python raises a SyntaxError because parentheses are mandatory

(B) It raises TypeError because a class object cannot be raised

(C) Python implicitly creates a ValueError() instance with no arguments and raises it

(D) Nothing happens until the class is called manually

Correct Answer: (C)

[EN] Passing an exception class to raise causes Python to call its zero-argument constructor automatically.

[HI] raise के साथ सीधे एक्सेप्शन क्लास देने पर पायथन स्वतः उसका बिना-आर्ग्यूमेंट वाला इंस्टेंस बनाकर उठाता है।

Q13. What does the BalanceError snippet above output if withdraw(500, 700) is called inside a try block catching BalanceError as e and printing str(e)?

(ऊपर दिए गए BalanceError कोड में यदि withdraw(500, 700) को try-except में पकड़कर str(e) प्रिंट किया जाए, तो आउटपुट क्या होगा?)

(A) None

(B) 700

(C) Short by 200

(D) ValueError: Short by 200

Correct Answer: (C)

[EN] 700 > 500 triggers raise BalanceError(500, 700), which passes f'Short by {700 - 500}' to super().__init__().

[HI] 700 > 500 होने पर BalanceError(500, 700) उठता है जो 'Short by 200' संदेश super().__init__() को देता है।

Q14. What happens if a bare raise is executed outside any active except block?

(यदि किसी सक्रिय except ब्लॉक के बाहर अकेला raise चलाया जाए तो क्या होगा?)

(A) RuntimeError: No active exception to reraise

(B) The previous script error from history is re-raised

(C) SystemExit(0) terminates the interpreter

(D) StopIteration is raised silently

Correct Answer: (A)

[EN] Without an active exception on the thread state, bare raise fails with RuntimeError.

[HI] जब कोई सक्रिय एक्सेप्शन मौजूद न हो, तो अकेला raise चलाने पर RuntimeError उत्पन्न होता है।

Q15. Which statement about Python exceptions and raise is NOT true?

(पायथन एक्सेप्शन और raise के संदर्भ में निम्नलिखित में से कौन-सा कथन असत्य है?)

(A) Custom exceptions must inherit directly from BaseException to be catchable

(B) Unchecked runtime errors propagate up the call stack until handled

(C) Custom exceptions can hold extra instance attributes like status_code

(D) A try block can catch custom exceptions by their parent Exception class

Correct Answer: (A)

[EN] Inheriting directly from BaseException is discouraged because except Exception would fail to catch it; Exception is the correct base.

[HI] कस्टम एक्सेप्शन को सीधे BaseException से इनहेरिट करना गलत है क्योंकि तब except Exception उसे पकड़ नहीं पाएगा।

Q16. Which attribute on an exception object stores the tuple of arguments passed when raising it?

(एक्सेप्शन ऑब्जेक्ट के किस एट्रिब्यूट में उसे बनाते समय दिए गए आर्ग्यूमेंट्स का टपल सहेजा जाता है?)

(A) context_tuple

(B) args

(C) params

(D) traceback_list

Correct Answer: (B)

[EN] Every BaseException instance stores constructor arguments inside the self.args tuple.

[HI] प्रत्येक BaseException इंस्टेंस अपने कंस्ट्रक्टर में मिले आर्ग्यूमेंट्स को self.args टपल में सुरक्षित रखता है।

Q17. Within Raising Exceptions (raise) and Custom User-Defined Exceptions, which construct / class directly maps to: "Throws a new exception instance immediately"?

(Raising Exceptions (raise) and Custom User-Defined Exceptions में कौन सा Construct / Class सीधे "Throws a new exception instance immediately" से संबंधित है?)

(A) class MyError(Exception)

(B) bare raise

(C) raise Exc('msg')

(D) raise A from B

Correct Answer: (C)

[EN] In Raising Exceptions (raise) and Custom User-Defined Exceptions, 'raise Exc('msg')' handles 'Throws a new exception instance immediately' (Unwinds stack to nearest matching except).

[HI] Raising Exceptions (raise) and Custom User-Defined Exceptions में 'raise Exc('msg')' का कार्य/विवरण 'Throws a new exception instance immediately' (Unwinds stack to nearest matching except) है।

Q18. Which option accurately describes 'bare raise' in Raising Exceptions (raise) and Custom User-Defined Exceptions?

(Raising Exceptions (raise) and Custom User-Defined Exceptions के संदर्भ में 'bare raise' की सही विशेषता कौन सी है?)

(A) Re-throws active exception inside except block

(B) Defines custom application exception class

(C) Throws a new exception instance immediately

(D) Chains explicit cause in A.__cause__

Correct Answer: (A)

[EN] 'bare raise' provides 'Re-throws active exception inside except block' — key point: Preserves original traceback without reset.

[HI] 'bare raise' का मुख्य विवरण 'Re-throws active exception inside except block' है (Preserves original traceback without reset)।

Q19. In Raising Exceptions (raise) and Custom User-Defined Exceptions, identify the correct parameter for the specification: "Chains explicit cause in A.__cause__".

(Raising Exceptions (raise) and Custom User-Defined Exceptions में "Chains explicit cause in A.__cause__" विवरण किस विकल्प के लिए सही है?)

(A) raise Exc('msg')

(B) class MyError(Exception)

(C) bare raise

(D) raise A from B

Correct Answer: (D)

[EN] 'raise A from B' corresponds to 'Chains explicit cause in A.__cause__' (Using from None sets __suppress_context__).

[HI] 'raise A from B' का संबंध 'Chains explicit cause in A.__cause__' (Using from None sets __suppress_context__) से है।

Q20. Considering Raising Exceptions (raise) and Custom User-Defined Exceptions, what key behavior defines 'class MyError(Exception)'?

(Raising Exceptions (raise) and Custom User-Defined Exceptions में 'class MyError(Exception)' की मुख्य भूमिका या मान क्या है?)

(A) Defines custom application exception class

(B) Throws a new exception instance immediately

(C) Re-throws active exception inside except block

(D) Chains explicit cause in A.__cause__

Correct Answer: (A)

[EN] 'class MyError(Exception)' represents 'Defines custom application exception class' (Avoid inheriting directly from BaseException).

[HI] 'class MyError(Exception)' का अर्थ/मान 'Defines custom application exception class' है (Avoid inheriting directly from BaseException)।

Raising Exceptions (raise) and Custom User-Defined Exceptions — Exam FAQs

Q1: Why is it bad practice to inherit custom exceptions directly from BaseException?

कस्टम एक्सेप्शन को सीधे BaseException से इनहेरिट करना गलत क्यों माना जाता है?

[EN] Standard handlers written as except Exception: will miss exceptions inheriting directly from BaseException, while BaseException is reserved for control-flow signals like SystemExit and KeyboardInterrupt.

[HI] सामान्य कोड में त्रुटियों को पकड़ने के लिए except Exception: लिखा जाता है। यदि कस्टम क्लास सीधे BaseException से बनेगी, तो वह except Exception से बच निकलेगी और Ctrl+C जैसे सिस्टम सिग्नल्स के स्तर पर चली जाएगी।

Q2: When should I use raise instead of assert in production code?

प्रोडक्शन कोड में assert के बजाय raise का उपयोग कब करना चाहिए?

[EN] Always use raise for user input validation, file/network checks, and business rules because assert statements are disabled when Python runs with the -O optimization flag.

[HI] यूजर इनपुट जांच, सुरक्षा नियंत्रण और बिजनेस लॉजिक के लिए हमेशा raise का उपयोग करें, क्योंकि python -O ऑप्टिमाइजेशन मोड में सभी assert स्टेटमेंट निष्क्रिय कर दिए जाते हैं।

Q3: What is the difference between __cause__ and __context__ in Python exceptions?

पायथन एक्सेप्शन में __cause__ और __context__ के बीच क्या अंतर है?

[EN] __cause__ is explicitly set using 'raise NewErr from OldErr', whereas __context__ is automatically populated whenever an exception occurs while another exception is already being handled.

[HI] __cause__ को 'raise NewErr from OldErr' लिखकर स्पष्ट रूप से सेट किया जाता है, जबकि किसी अन्य एक्सेप्शन को संभालते समय अनजाने में नया एक्सेप्शन आने पर पायथन स्वतः __context__ सेट करता है।

Related Posts

  • Loading related posts...

Post a Comment

Search Topic Notes & 20 MCQs (Hindi / English)