Class XII · Chapter 1Unit 1, Computational Thinking and Programming, 2 (40 marks)5 min read
Share:WhatsAppLinkedIn

Chapter 1: Exception Handling in Python

CBSE Unit: Unit 1, Computational Thinking and Programming, 2 (40 marks) Marks Weightage: ~3-5 marks (1 MCQ + 1 short answer typically) Priority: HIGH, small chapter but guaranteed questions


Key Concepts

1.1 Syntax Errors vs Exceptions

  • Syntax errors (parsing errors): detected before execution, program won't run until fixed
  • Exceptions: errors during execution of syntactically correct code (runtime errors)
  • Important: SyntaxError is technically also an exception, but all other exceptions occur when code is syntactically correct

1.2 Built-in Exceptions (MUST memorize)

Exception When Raised Example
SyntaxError Rules of language not followed print("hello" (missing parenthesis)
ValueError Right type but wrong value int("hello")
IOError File cannot be opened open("nonexistent.txt")
KeyboardInterrupt User presses Delete/Esc during execution Ctrl+C during input()
ImportError Module not found import nonexistent_module
EOFError End of file reached by input() Ctrl+D during input()
ZeroDivisionError Division by zero 10/0
IndexError Index out of range lst[100] on small list
NameError Variable not defined Using x without defining it
IndentationError Incorrect indentation Missing indent after if:
TypeError Wrong data type for operation "hello" + 5
OverFlowError Result exceeds numeric limit Very large calculations

1.3 Raising Exceptions

The raise Statement

raise exception_name[(optional_argument)]
  • Forces an exception to be raised, Statements after raise are NOT executed, Can raise built-in or user-defined exceptions
# Example
length = 10
numbers = [1, 2, 3]
if length > len(numbers):
    raise IndexError("List index out of range")
print("This will NOT execute")

The assert Statement

assert Expression[, arguments]
  • Tests an expression, if False, raises AssertionError
  • Commonly used at beginning of functions to validate input
def negativecheck(number):
    assert(number >= 0), "OOPS... Negative Number"
    print(number * number)

negativecheck(100)   # Output: 10000
negativecheck(-350)  # AssertionError: OOPS... Negative Number

1.4 Handling Exceptions, try/except/else/finally

Basic try-except

try:
    # code that might raise exception
    numerator = 50
    denom = int(input("Enter denominator: "))
    quotient = numerator / denom
    print("Division successful")
except ZeroDivisionError:
    print("Cannot divide by zero!")
print("This executes regardless")

Multiple except blocks

try:
    numerator = 50
    denom = int(input("Enter denominator: "))
    print(numerator / denom)
except ZeroDivisionError:
    print("Cannot divide by zero")
except ValueError:
    print("Only integers allowed")

Generic except (catch-all), must be LAST

try:
    # code
except ValueError:
    print("Value error")
except:
    print("Some other error occurred")

try-except-else

  • else block executes ONLY if NO exception was raised in try
try:
    quotient = numerator / denom
except ZeroDivisionError:
    print("Cannot divide by zero")
else:
    print("Result is:", quotient)  # Only if no error

try-except-else-finally

  • finally block ALWAYS executes, with or without exception, Used for cleanup operations (closing files, releasing resources)
try:
    quotient = numerator / denom
except ZeroDivisionError:
    print("Cannot divide by zero")
else:
    print("Result:", quotient)
finally:
    print("This ALWAYS executes")

Critical point: If exception is raised and NO matching except handler exists, the finally block still executes FIRST, then the exception is re-raised.


Flow Summary

try block → (exception?) → YES → matching except block → finally
                         → NO  → else block → finally

Important Definitions for Board Exam

Term Definition
Exception A Python object that represents an error during execution
Exception Handling Writing additional code to handle errors and prevent program crash
Throwing an exception Creating an exception object and handing it to runtime system
Catching an exception Executing the handler code designed for that exception
Call stack The list of methods searched (in reverse order) to find exception handler

Common Board Exam Question Patterns

  1. MCQ: Which exception is raised when... (1 mark)
  2. MCQ: What is the output of code with try-except? (1 mark)
  3. Fill in blanks: Complete a try-except-else-finally block (2 marks)
  4. Short answer: Differentiate between syntax error and exception (2 marks)
  5. Short answer: What is the use of raise/assert statement? (2 marks)
  6. Program: Write code with exception handling for division/file/input (3 marks)

Key Points Students Miss

  1. finally executes even if exception is NOT handled by any except block
  2. else executes only when NO exception occurs, not "otherwise"
  3. After raise, remaining statements in that block are skipped
  4. assert raises AssertionError specifically, not a generic error
  5. Multiple except blocks: order matters, generic except: must be LAST
  6. SyntaxError IS an exception (confuses students who think only runtime errors are exceptions)

Exercise Answers (Key)

Q1: "Every syntax error is an exception but every exception cannot be a syntax error", SyntaxError is a type of exception. But exceptions like ValueError, ZeroDivisionError etc. are not syntax errors, they occur in syntactically correct code.

Q7 Fill in blanks: ValueError, ZeroDivisionError, finally

Test Your Knowledge

Take a quick quiz on this chapter

Start Quiz →

Prefer watching over reading?

Subscribe for free.

Subscribe on YouTube