Follow Us
माध्यम चुनें / Select Medium:
Eng (English) Hindi (हिन्दी)
CBSE • कक्षा XII • Computer Science • अध्याय 1
अनुमानित समय: 45 Mins
प्रगति: अध्ययनरत

पायथन में अपवाद प्रबंधन (Exception Handling)

In CBSE Class 12 Computer Science, "Exception Handling in Python" provides an exhaustive master resource on building resilient, fault-tolerant software. This chapter covers syntax vs runtime exceptions, the complete Python Exception Hierarchy (`BaseException` to `Exception`), structured handling using `try`, `except`, `else`, and `finally` blocks, raising custom exceptions via `raise`, defining user-defined exception classes, the `assert` statement for defensive programming, and resource cleanup mechanics aligned with the 2026–27 CBSE curriculum.

Why Can a Single Division by Zero Crash an Entire Hospital or Banking System?

In 1997, the guided missile cruiser USS Yorktown suffered a total propulsion and network failure in the Atlantic Ocean, turning the entire warship into a drifting steel deadweight. The cause was not an enemy torpedo or hardware fire; it was a single sailor typing a zero into an input field on a Windows terminal, triggering an unhandled "Division by Zero" arithmetic exception that cascaded through the control software, crashing every connected system. In professional programming, errors are not accidents—they are inevitable real-world events. Disks fill up, network connections drop, and users type text into number fields. How do software engineers write code that catches errors gracefully, cleans up open database connections, and keeps critical systems running 24/7 without crashing? This chapter masters modern exception handling.

यह अध्याय क्यों महत्वपूर्ण है

Writing code that works under perfect conditions is easy; writing code that gracefully recovers from unexpected real-world failures is the defining mark of a professional software engineer. In commercial production systems, an unhandled exception causes application downtime, financial transaction failure, and security vulnerabilities. Mastering the `try-except-else-finally` block lifecycle ensures that files and database connections are always safely closed, custom business rules are enforced via user-defined exceptions, and software remains rock-solid in mission-critical environments.

अध्ययन से पूर्व (आवश्यक ज्ञान)

  • Fundamental Python syntax, functions, and standard I/O.
  • Knowledge of flow of control and conditional branching.
  • Familiarity with standard runtime errors from Class 11 (`ValueError`, `TypeError`, `IndexError`).

इस अध्याय के लक्ष्य

  • Differentiate between Compile-time/Syntax Errors, Runtime Exceptions, and Logical Bugs.
  • Trace the standard Python Exception Hierarchy from `BaseException` down to specific built-in subclasses.
  • Construct robust exception-handling blocks using `try`, multiple `except` handlers, `else`, and `finally`.
  • Analyze the execution guarantee of the `finally` block even when `return`, `break`, or unhandled exceptions occur.
  • Raise built-in and user-defined custom exceptions using the `raise` keyword.
  • Implement defensive validation using the `assert` statement and handle `AssertionError`.
  • Create custom application exception classes by inheriting from Python's built-in `Exception` superclass.

अध्याय रूपरेखा एवं प्रगति

1 1. Errors vs. Exceptions & The Pyth...
2 2. The Complete `try-except-else-fi...
3 3. Raising Exceptions & The `assert...
4 4. Engineering Custom User-Defined...

सम्पूर्ण सैद्धांतिक एवं वैचारिक अध्ययन

1. Errors vs. Exceptions & The Python Exception Hierarchy

Understand

In software development, anomalous execution events are divided into two categories:

  • Syntax Errors (Parsing Errors): Violations of Python's formal grammar (e.g., missing colons, mismatched parentheses, invalid indentation). Caught by the tokenizer/parser *prior* to program execution. Execution cannot begin until all syntax errors are resolved.
  • Exceptions (Runtime Errors): Disruptive events that occur *during* program execution when syntactically valid code attempts an illegal operation (e.g., dividing by zero, opening a non-existent file, indexing an empty list). If not caught by an exception handler, the Python interpreter halts execution and prints a diagnostic Traceback.
The Python Built-in Exception Hierarchy

All Python exceptions are classes organized in a strict object-oriented inheritance tree rooted at BaseException:

BaseException
 ├── SystemExit (Triggered by sys.exit())
 ├── KeyboardInterrupt (Triggered by Ctrl+C in terminal)
 └── Exception (Root superclass for all non-fatal application exceptions)
      ├── ArithmeticError
      │    ├── ZeroDivisionError (e.g., 10 / 0)
      │    └── OverflowError (Calculation exceeds floating-point limits)
      ├── LookupError
      │    ├── IndexError (Sequence index out of range)
      │    └── KeyError (Dictionary key not found)
      ├── ValueError (Correct type, but invalid value, e.g., int("abc"))
      ├── TypeError (Operation applied to inappropriate data type)
      ├── NameError (Identifier not found in any LEGB scope)
      └── OSError
           ├── FileNotFoundError (File path does not exist)
           └── PermissionError (Insufficient OS file access rights)

2. The Complete `try-except-else-finally` Lifecycle

Understand & Deep Dive

Python provides a 4-clause structured mechanism to anticipate and handle runtime exceptions gracefully:

try:
    # 1. Critical code that might raise an exception
    num = int(input("Enter numerator: "))
    den = int(input("Enter denominator: "))
    result = num / den
except ZeroDivisionError as zde:
    # 2. Handles division by zero specifically
    print(f"Math Error: Cannot divide by zero! ({zde})")
except ValueError as ve:
    # 3. Handles invalid alphanumeric conversion
    print(f"Input Error: Please enter valid integer digits only! ({ve})")
except Exception as e:
    # 4. Fallback handler for any other unexpected Exception subclass
    print(f"Unexpected Error occurred: {type(e).name} - {e}")
else:
    # 5. Executes ONLY if the try block completed with ZERO exceptions!
    print(f"Success! Calculation result = {result:.4f}")
finally:
    # 6. GUARANTEED EXECUTION! Always runs, whether an error occurred or not!
    print("Cleanup: Calculation transaction completed. Releasing locks.")
The `finally` Block Guarantee

The `finally` clause is critical for resource management (closing files, releasing database locks, terminating network sockets). It executes under all conditions—even if the `try` block executes an abrupt `return`, `break`, or raises an unhandled fatal error!

3. Raising Exceptions & The `assert` Statement

Understand
A. The `raise` Statement

You can deliberately trigger an exception when program logic detects an illegal business state using the `raise` keyword:

def withdraw_money(balance, amount):
    if amount <= 0:
        raise ValueError("Withdrawal amount must be strictly positive!")
    if amount > balance:
        raise ValueError(f"Insufficient funds! Requested {amount}, Available {balance}")
    return balance - amount
B. Defensive Programming with `assert`

The `assert condition, "Error Message"` statement tests an internal diagnostic assumption. If the condition is `False`, Python immediately raises an AssertionError:

def calculate_discount(price, discount_percent):
    assert 0 <= discount_percent <= 100, "Discount percentage must be between 0 and 100!"
    return price * (1 - discount_percent / 100)

4. Engineering Custom User-Defined Exceptions

Understand & Enterprise Design

In enterprise software engineering, standard built-in exceptions like `ValueError` are too generic to describe specific business domain failures. You create Custom Exceptions by defining a new class that inherits directly from Python's built-in Exception class:

# 1. Define custom domain exceptions inheriting from Exception:
class InvalidAgeError(Exception):
    """Raised when an applicant's age is outside legal limits."""
    pass

class UnderageVotingError(InvalidAgeError):
    """Raised when a citizen attempts voting under age 18."""
    def init(self, age, message="Citizen is below legal voting age (18)."):
        self.age = age
        self.message = f"{message} Current age: {age}"
        super().init(self.message)

# 2. Utilize the custom exception in business logic:
def cast_vote(citizen_name, age):
    if age < 0 or age > 120:
        raise InvalidAgeError(f"Absurd age entered: {age}")
    if age < 18:
        raise UnderageVotingError(age)
    print(f"Vote successfully recorded for {citizen_name}!")

try:
    cast_vote("Rohan", 16)
except UnderageVotingError as uve:
    print(f"Election Commission Alert: {uve}")

प्रोग्रामिंग सिंटेक्स, स्टेटमेंट्स एवं भाषा अनुवादक नियम

Exception Handling Flow
$$\text{try} \to (\text{except} \lor \text{else}) \to \text{finally}$$
Canonical execution lifecycle of structured Python exception blocks.
Assert Verification Law
$$\text{assert } P, M \iff \text{if not } P: \text{raise AssertionError}(M)$$
Exact equivalence of the assert statement.

Python Exception Handling Lifecycle Flowchart

Python Exception Lifecycle: try - except - else - finally try: Critical Code Block Exception Raised? YES (Error) except: Handler Matches NO (Success) else: Runs on Success finally: ALWAYS EXECUTES Guaranteed Resource Cleanup (Close Files & DB Sockets)

अध्याय का सार संक्षेप एवं 10 मुख्य निष्कर्ष

मुख्य बिंदु 1
Syntax errors violate language grammar before execution; runtime exceptions occur during execution of valid code.
मुख्य बिंदु 2
An unhandled exception terminates program execution and emits a diagnostic traceback.
मुख्य बिंदु 3
The Python Exception hierarchy is rooted at `BaseException`, with standard application errors inheriting from `Exception`.
मुख्य बिंदु 4
The `try` block wraps code that may raise an exception; `except` catches and handles specific exception types.
मुख्य बिंदु 5
A single `try` statement can feature multiple `except` handlers to handle different error types distinctively.
मुख्य बिंदु 6
The `else` clause executes only if the `try` block completes successfully without raising any exceptions.
मुख्य बिंदु 7
The `finally` clause is guaranteed to execute under all conditions, making it essential for resource cleanup.
मुख्य बिंदु 8
The `raise` statement allows programmers to deliberately trigger built-in or custom exceptions.
मुख्य बिंदु 9
The `assert condition, message` statement provides defensive assertion checks, raising `AssertionError` if false.
मुख्य बिंदु 10
Custom exceptions are created by subclassing the standard `Exception` class, enabling fine-grained business logic error handling.

स्व-मूल्यांकन अभ्यास (Check Your Understanding)

मूल वैचारिक स्पष्टता की जांच के लिए नैदानिक प्रश्न। पहले स्वयं हल करें, फिर उत्तर देखें।

1
Explain the exact sequence of execution among `try`, `except`, `else`, and `finally` blocks when: (a) No exception occurs, and (b) An anticipated exception occurs.
उत्तर एवं व्याख्या देखें
उत्तर: (a) When No Exception Occurs: The `try` block executes completely → All `except` blocks are skipped → The `else` block executes → The `finally` block executes.
(b) When An Anticipated Exception Occurs: The `try` block executes up to the error line and halts → The matching `except` block executes → The `else` block is skipped → The `finally` block executes.
try → else → finally on success; try → except → finally on error.
2
Why should software developers avoid using a bare `except:` without specifying an exception class?
उत्तर एवं व्याख्या देखें
उत्तर: A bare `except:` catches *every* exception derived from `BaseException`—including critical system signals like `KeyboardInterrupt` (Ctrl+C to stop a program) and `SystemExit`. This makes the program immune to normal terminal termination, hides serious syntax/logic bugs, and makes debugging almost impossible. Best practice requires catching specific exceptions (e.g., `except ValueError:`) or at minimum `except Exception:`.
Bare except catches KeyboardInterrupt and SystemExit, preventing normal program termination.
3
Predict the exact output of the following code snippet containing a return statement inside the `try` block:
def test_finally():
    try:
        print("Inside Try")
        return 1
    finally:
        print("Inside Finally")

print("Returned:", test_finally())
उत्तर एवं व्याख्या देखें
उत्तर: Output:
Inside Try
Inside Finally
Returned: 1
Explanation: Even though the `try` block encounters a `return 1` statement, Python guarantees that the `finally` block executes before the function actually exits and transfers control back to the caller.
finally is guaranteed to execute before the return statement exits the function.
4
What is the purpose of the `assert` statement in Python? How does it differ from a standard `if-else` check?
उत्तर एवं व्याख्या देखें
उत्तर: The `assert` statement is a debugging and defensive programming tool used to verify internal program assumptions that *should always be True* if the code is bug-free. If the assertion fails, it immediately raises an `AssertionError`. In contrast, `if-else` handles expected real-world user or runtime conditions gracefully. Assertions can be globally disabled in production environments by running Python with the optimization flag (`python -O`).
assert is for internal developer assumptions during debugging; if-else handles runtime user conditions.
5
Write a Python program that prompts the user for two integers and divides them, handling both `ZeroDivisionError` and `ValueError` with custom user-friendly messages.
उत्तर एवं व्याख्या देखें
उत्तर:
try:
    a = int(input("Enter first integer: "))
    b = int(input("Enter second integer: "))
    result = a / b
except ZeroDivisionError:
    print("Error: Cannot divide any number by zero!")
except ValueError:
    print("Error: Invalid input! You must enter whole integer numbers.")
else:
    print(f"Division result: {result}")
finally:
    print("Execution completed.")

Wrap input and division inside try; catch ZeroDivisionError and ValueError separately.
6
How do you create a custom user-defined exception in Python? Provide a complete code example of a `NegativeNumberError`.
उत्तर एवं व्याख्या देखें
उत्तर:
class NegativeNumberError(Exception):
    """Exception raised for negative numerical inputs."""
    def init(self, value, message="Negative numbers are strictly prohibited!"):
        self.value = value
        self.message = f"{message} (Received: {value})"
        super().init(self.message)

def compute_square_root(n):
    if n < 0:
        raise NegativeNumberError(n)
    return n ** 0.5

try:
    print(compute_square_root(-25))
except NegativeNumberError as e:
    print("Caught Custom Exception:", e)

Subclass Exception, implement init, and trigger using raise.

7
What is the significance of the `as` keyword in an `except ExceptionName as e:` statement?
उत्तर एवं व्याख्या देखें
उत्तर:

The as keyword binds the caught exception instance to a local variable (commonly named e or err). This allows the programmer to inspect the actual error message, error arguments (e.args), or error class name (type(e).name), and log the diagnostic technical details to a file.


Binds the runtime exception instance to a variable for diagnostic inspection.
8
Explain the order of `except` blocks when handling exceptions with an inheritance relationship (e.g., `ArithmeticError` and `ZeroDivisionError`). What happens if the parent is placed before the child?
उत्तर एवं व्याख्या देखें
उत्तर: In Python, `except` blocks are evaluated from top to bottom. Because `ZeroDivisionError` is a subclass of `ArithmeticError`, placing `except ArithmeticError:` before `except ZeroDivisionError:` causes the parent block to intercept all division-by-zero errors, rendering the specialized child block unreachable (dead code). Child exceptions must always be caught BEFORE parent superclass exceptions.
Child exceptions must precede parent exceptions in the handler chain to avoid shadowing.
अध्याय का अध्ययन पूर्ण हुआ?
अभ्यास के लिए तैयार?

ऑनलाइन CBT टेस्ट देकर तैयारी का मूल्यांकन करें

झारखण्ड बोर्ड परीक्षा पैटर्न पर आधारित बहुविकल्पीय प्रश्नों का ऑनलाइन टेस्ट दें। तुरंत परिणाम, समय विश्लेषण और प्रत्येक प्रश्न का विस्तृत हल प्राप्त करें।

AI अध्ययन मित्र

त्वरित शंका समाधान

पायथन में अपवाद प्रबंधन (Exception Handling) में कोई संदेह या प्रश्न है? हमारे AI अध्ययन मित्र से तुरंत समझें।