📌 Snapshot
- Exception handling is a structured approach to runtime errors in Python programs.
- Syntax errors are detected before execution; exceptions are raised during execution of syntactically correct code.
- Python has a built-in exception hierarchy (12 common exceptions); raise exceptions programmatically using
raiseandassert. - The core construct is
try...except...else...finally, which CUET tests both in code-tracing and definition-based questions. - Knowing which clause executes under which condition (error vs. no error vs. always) is the single most-tested skill here.
📖 Detailed Notes
2.1 Core concepts
- Introduction to errors: A Python program may fail to execute at all, or may execute but produce unexpected output. This happens due to syntax errors, runtime errors, or logical errors. In Python, exceptions are errors triggered automatically; they can also be forcefully triggered and handled through program code. (NCERT §1.1, p. 1)
- Syntax errors (parsing errors): Detected when the programmer has not followed the rules of the language while writing the program. The interpreter does not execute the program until syntax errors are rectified. In shell mode, Python displays the error name and a brief description. In script mode, a dialog box with the error name and description is shown. (NCERT §1.2, pp. 1–2)
- Exceptions: Even if a statement is syntactically correct, an error may arise during execution — for example, dividing by zero or opening a non-existent file. Such errors disrupt normal execution and are called exceptions. An exception is a Python object that represents an error; when raised, it must be handled by the programmer to prevent abnormal termination. SyntaxError shown in Figures 1.1 and 1.3 is itself an exception, but all other exceptions are generated only when the program is syntactically correct. (NCERT §1.3, p. 3)
- Built-in exceptions: Python's standard library provides an extensive collection of built-in exceptions for commonly occurring errors. On occurrence, the interpreter displays the raised exception name and reason; 12 common built-in exceptions are listed in Table 1.1: SyntaxError, ValueError, IOError, KeyboardInterrupt, ImportError, EOFError, ZeroDivisionError, IndexError, NameError, IndentationError, TypeError, and OverFlowError. Programmers can also create user-defined (custom) exceptions. (NCERT §1.4, pp. 3–4)
- Raising exceptions —
raisestatement: Each time an error is detected, the Python interpreter raises (throws) an exception. Programmers can also forcefully raise exceptions usingraiseandassert. Raising an exception interrupts normal program flow and jumps to the exception handler code. Once raised, no further statement in the current block is executed. Syntax:raise exception-name[(optional argument)]. The optional argument is typically a string message displayed when the exception is raised. Whenraise IndexErroris used explicitly, a stack Traceback is displayed showing the sequence of function calls. (NCERT §1.5, §1.5.1, pp. 4–5) assertstatement: Used to test an expression in program code. If the expression evaluates to False, anAssertionErrorexception is raised. Used at the beginning of a function or after a function call to check for valid input. Syntax:assert Expression[, arguments]. On passing a negative value in Program 1-1,AssertionError: OOPS... Negative Numberis raised and subsequent statements are not executed. (NCERT §1.5.2, pp. 6–7)- Need for exception handling: Exception handling is used in Python and most programming languages (C++, Java, Ruby). It captures runtime errors and prevents the program from crashing. Python categorises exceptions into distinct types; exception handlers separate error-detection code from main logic; the compiler/interpreter tracks the exact error position; both user-defined and built-in exceptions can be handled. (NCERT §1.6.1, p. 7)
- Process of handling exceptions: When an error occurs, the Python interpreter creates an exception object containing error type, file name, and position. This object is handed to the runtime system — the act of creating and passing it is called throwing an exception. The runtime system searches for an exception handler in the current method; if not found, it searches the call stack in reverse order (forwarding the exception). Executing a suitable handler is called catching the exception. If no handler is found in the entire call stack, the program terminates. (NCERT §1.6.2, pp. 7–9)
- Catching exceptions —
try...exceptblock: Suspicious code is placed inside atryblock; everytryblock is followed by one or moreexceptblocks containing handler code. When an exception occurs in thetryblock, execution stops and control transfers to the matchingexceptblock. After theexceptblock executes, the statement following thetry...exceptconstruct runs normally. Multipleexceptblocks can handle different exceptions for a singletryblock. Anexceptclause without a named exception acts as a catch-all and should be placed last. (NCERT §1.6.3, pp. 9–12) try...except...elseclause: An optionalelseblock can follow theexceptblocks. Theelseblock executes only if no exception is raised in thetryblock; if an exception is raised, theelseblock is skipped. (NCERT §1.6.4, pp. 12–13)finallyclause: Thetrystatement can have an optionalfinallyclause whose statements are always executed regardless of whether an exception occurred in thetryblock. It is a common practice to usefinallywith file operations to ensure the file object is closed.finallymust be placed at the end of thetryclause, after allexceptblocks and theelseblock. If an exception is not handled by anyexceptclause, it is re-raised after thefinallyblock executes. (NCERT §1.7, §1.7.1, pp. 13–15)
2.2 Definitions to memorise
| Term | Definition | Page |
|---|---|---|
| Syntax Error | An error detected when the rules of the programming language are not followed while writing the program; also called a parsing error. | 1 |
| Exception | A Python object that represents an error occurring during program execution even when the statement is syntactically correct. | 3 |
| Built-in Exception | Commonly occurring exceptions defined in Python's standard library/interpreter that provide standardised handling for typical errors. | 3 |
| Exception Handler | Code designed to execute when a specific exception is raised; separates error-correction logic from main program logic. | 7 |
| Throwing an Exception | The process of creating an exception object and handing it over to the runtime system when an error occurs. | 8 |
| Catching an Exception | The process of executing a suitable exception handler found in the call stack. | 8–9 |
| Call Stack | The entire list of methods searched in reverse hierarchical order when an exception handler is not found in the current method. | 8 |
| raise Statement | A Python statement used to forcefully throw an exception; syntax: raise exception-name[(optional argument)]. |
5 |
| assert Statement | A Python statement that tests an expression; raises AssertionError if the expression evaluates to False. |
6 |
| finally Clause | An optional clause in a try statement whose code always executes regardless of whether an exception was raised or not. | 13 |
| User-defined Exception | A custom exception created by a programmer to suit specific requirements, as opposed to a built-in exception. | 4 |
try block |
Block of code in which suspicious statements that may raise exceptions are placed | 9 |
except block |
Block following try that handles a specific exception |
10 |
else block |
Optional clause after all except blocks that runs only when no exception was raised |
12 |
| ZeroDivisionError | Built-in exception raised when the denominator in a division is zero | 4 |
| ValueError | Built-in exception raised when a function receives an argument of correct type but inappropriate value | 4 |
| TypeError | Built-in exception raised when an operator is applied to a value of incorrect data type | 4 |
| IndexError | Built-in exception raised when a sequence subscript is out of range | 4 |
| NameError | Built-in exception raised when a local or global name is not defined | 4 |
| IOError | Built-in exception raised when an I/O operation fails (e.g., file not found) | 4 |
| ImportError | Built-in exception raised when an import statement cannot find the module | 4 |
| OverflowError | Built-in exception raised when arithmetic result exceeds numeric type limits | 4 |
| KeyboardInterrupt | Built-in exception raised when the user interrupts execution (Delete/Esc) | 4 |
| EOFError | Built-in exception raised when input() hits end-of-file unexpectedly | 4 |
| AssertionError | Built-in exception raised when an assert expression evaluates to False | 6 |
| Stack Traceback | Sequence of function calls printed when an exception propagates uncaught | 5 |
2.3 Diagrams / processes to remember
- Figure 1.1 (p. 2): Screenshot showing a SyntaxError in Python shell mode — "Missing parentheses in call to 'print'" — illustrating how the interpreter reports a syntax error with a brief explanation and suggestion.
- Figure 1.4 (p. 4): Screenshot demonstrating three built-in exceptions raised in a single shell session:
ZeroDivisionError(print(50/0)),NameError(print(var+40)), andTypeError(10+'5') — key for identifying which exception corresponds to which error condition. - Figure 1.8 (p. 9): Flowchart of the exception handling process — the most important diagram. Flow: error encountered → create exception object → exception raised → runtime searches current method → if found, execute handler (catching); if not found, search call stack in reverse (forwarding) → if still not found, program terminates.
- Figure 1.12 (p. 13): Output of Program 1-5 showing
try...except...elsebehaviour — when no exception occurs, theelseblock prints the quotient. - Figure 1.13 (p. 15): Output of Program 1-7 demonstrating
finallyclause recovery — "OVER AND OUT" prints even when aValueErroris raised, then the exception is re-raised.
2.4 Common confusions / NTA trap points
- SyntaxError is also an exception: Students often think SyntaxError and exceptions are mutually exclusive. SyntaxError (shown in Figs. 1.1 and 1.3) is also an exception. However, all exceptions other than SyntaxError are generated only when the program is syntactically correct. (p. 3)
elsevs.finallyexecution conditions: Theelseblock runs only when NO exception is raised intry. Thefinallyblock runs ALWAYS — whether or not an exception occurred. NTA may swap these in options.finallydoes not suppress unhandled exceptions: If an exception is not caught by anyexceptclause,finallyexecutes first and then the exception is re-raised. Thefinallyclause does NOT terminate (handle) the exception — unlikeexcept.raisestops all further execution in the block: After araisestatement, no subsequent statement in the current block executes (theprint("NO EXECUTION")in Figure 1.6 is never reached). NTA may ask what output a code snippet produces whenraiseappears mid-block.- Bare
except:clause order (NCERT §1.6.3, p. 11). Anexceptclause without a named exception must always be the LAST except block; placing it before specific handlers would shadow them. - One
exceptmatches per try (NCERT §1.6.3, p. 11). Only the first matchingexceptblock runs; the others are skipped. - Errors before
tryare not caught (NCERT §1.6.3, p. 9). A statement before thetryblock that raises an error is NOT caught — thetrymust surround the suspicious code. finallyALWAYS runs (NCERT §1.7, p. 13). Including after a successfultry, after anexcepthandler, and even when an unhandled exception propagates.- Unhandled exceptions terminate the program (NCERT §1.6.2, p. 8). If no matching handler is found anywhere in the call stack, Python prints the traceback and exits.
assert≠if(NCERT §1.5.2, p. 6).assertis for debugging/validation — it raises an AssertionError.ifis for normal flow.raisewith no exception name re-raises the current exception (Python convention; NCERT mentions raise with name). NCERT focuses onraise ExceptionName.
🎯 Practice MCQs
First 3 questions free · create a free account to unlock the rest — answers & explanations included, no payment needed
Q1. Which of the following statements about syntax errors in Python is correct?
▸ Show answer & explanation
Answer: B
Syntax errors are also called "parsing errors"; the interpreter does not execute the program unless they are rectified. Option C incorrectly describes runtime exceptions; Option D is wrong because Figure 1.1 shows a syntax error in shell mode. ---
Q2. Consider the following code: ```python numbers = [40, 50, 60, 70] length = 10 if length > len(numbers): raise IndexError print("NO EXECUTION") else: print(length) ``` What will be the output?
▸ Show answer & explanation
Answer: D
Since `length (10) > len(numbers) (4)`, `raise IndexError` executes. Once an exception is raised, no further statement in the current block is executed, so "NO EXECUTION" is never printed. Option C is wrong because the print after raise is not reached. ---
Q3. Which of the following correctly describes the `assert` statement in Python?
▸ Show answer & explanation
Answer: B
`assert` raises `AssertionError` (not `ValueError`) when the tested expression is False. Option D is wrong; assert is used "in the beginning of the function or after a function call to check for valid input." ---
🔒 12 more practice MCQs
Create a free account to unlock every MCQ in this chapter — answers and explanations included. No payment needed.
Already registered? Just log in and they'll all appear here.
Q4. Which of the following pairs of built-in exceptions and their triggering conditions is INCORRECTLY matched?
▸ Show answer & explanation
Answer: C
ImportError is raised when the requested module definition is not found (Table 1.1, entry 5). The description in Option C matches EOFError (Table 1.1, entry 6). Options A, B, and D are correctly matched per Table 1.1. ---
Q5. Read the following statements about exception handling and identify which ones are correct. **Statement I:** The `else` block in a `try...except...else` construct executes only if no exception is raised in the `try` block. **Statement II:** The `finally` block executes only if an exception is raised in the `try` block.
▸ Show answer & explanation
Answer: B
Statement I is correct per §1.6.4: "if there is no error then none of the except blocks will be executed. In this case, the statements inside the else clause will be executed." Statement II is incorrect: §1.7 states "The statements inside the finally block are always executed regardless of whether an exception has occurred in the try block or not." ---
Q6. In the exception handling flowchart (Figure 1.8), if the runtime system does NOT find an exception handler in the current method, what does it do next?
▸ Show answer & explanation
Answer: C
According to the exception handling flowchart (Fig. 1.8), when a handler is not found in the current method, the runtime system searches the call stack in reverse sequence — a process called "forwarding the exception." Only if no handler is found anywhere in the call stack does the program terminate. ---
Q7. Match the following Python exception names with their correct descriptions: | List I | List II | |---|---| | P. NameError | 1. Raised when a local or global variable name is not defined | | Q. IndentationError | 2. Raised when result of a calculation exceeds the maximum limit for numeric data type | | R. OverFlowError | 3. Raised due to incorrect indentation in the program code | | S. KeyboardInterrupt | 4. Raised when the user accidentally hits the Delete or Esc key while executing a program |
▸ Show answer & explanation
Answer: A
Per Table 1.1: NameError (entry 9) — variable not defined; IndentationError (entry 10) — incorrect indentation; OverFlowError (entry 12) — exceeds maximum numeric limit; KeyboardInterrupt (entry 4) — user presses Delete/Esc key. ---
Q8. Study the following code: ```python try: numerator = 50 denom = int(input("Enter the denominator: ")) quotient = (numerator / denom) print("Division performed successfully") except ZeroDivisionError: print("Denominator as ZERO is not allowed") except ValueError: print("Only INTEGERS should be entered") except: print("OOPS.....SOME EXCEPTION RAISED") print("OUTSIDE try..except block") ``` If the user enters `0` as the denominator, what will be printed?
▸ Show answer & explanation
Answer: B
Entering 0 raises `ZeroDivisionError`. The first matching `except` block prints "Denominator as ZERO is not allowed." After the except block, the statement outside the try..except construct ("OUTSIDE try..except block") executes normally. Option C would occur only if the exception raised has no specific matching handler (e.g., a non-ZeroDivisionError, non-ValueError exception). ---
Q9. Output: ```python try: print(10/2) except ZeroDivisionError: print("Zero!") else: print("OK") ```
▸ Show answer & explanation
Answer: B
No exception → `else` runs after the try. ---
Q10. Output: ```python try: x = int("abc") except ValueError: print("VAL") finally: print("FIN") ```
▸ Show answer & explanation
Answer: C
`int("abc")` raises ValueError → handler runs, then `finally` runs. ---
Q11. Which exception is raised by `10 + '5'`?
▸ Show answer & explanation
Answer: C
Q12. The order of `except` blocks matters because:
▸ Show answer & explanation
Answer: B
Q13. Output: ```python try: raise IndexError("Bad") print("Unreached") except IndexError as e: print("Caught", e) ```
▸ Show answer & explanation
Answer: A
After `raise`, the next statement does not execute. ---
Q14. Assertion (A): `finally` is the right place to close resources like files. Reason (R): `finally` runs regardless of whether the try block succeeded or raised an exception.
▸ Show answer & explanation
Answer: A
Q15. Which is NOT a built-in exception listed in Table 1.1?
▸ Show answer & explanation
Answer: C
📊 Previous-Year Questions
Practise with real CUET Computer Science previous-year papers — every question solved, with the correct answer and a step-by-step explanation.
View solved CUET PYQ papers →Ready to drill Computer Science?
Unlock all MCQs, chapter tests, mocks & PYQs for ₹199/year.
Get UniDrill Pro