Skip to content
Computer ScienceCBSE Class 12 · Chapter 3

Exception Handling in Python: CBSE Class 12 Computer Science

Updated 14 October 2026 · Fact-checked

An exception is an error that occurs while a program runs, such as dividing by zero or opening a missing file. Python lets you handle it with try-except-finally: risky code goes in try, the response to a named exception goes in except, and code that must always run goes in finally, so the program does not crash.

What Exception Handling in Python is about

Exception Handling in Python is the third chapter of Unit 1 and the first chapter of the NCERT Class XII book. It is short, but it is tested in Section A (MCQs and assertion-reason on which block runs), in Section B (output of a try-except-finally program) and inside file and Python-SQL programs, where a try block protects the file or database work.

The syllabus wording is "Introduction, handling exceptions using try-except-finally blocks". So you need:

  • the difference between a syntax error (found before the program runs) and an exception (raised while it runs)
  • the common built-in exceptions: SyntaxError, ValueError, IOError, KeyboardInterrupt, ImportError, EOFError, ZeroDivisionError, IndexError, NameError, IndentationError, TypeError, OverflowError, and the everyday KeyError and FileNotFoundError
  • try-except: one or several except blocks, and a bare except that catches everything
  • finally: the block that runs whether or not an exception occurred, even after return
  • the flow of control: which lines run, which are skipped, and what happens when no except matches

The statements raise and assert (NCERT 1.5) are not named in the 2026-27 syllabus, so this page does not test them.

Weightage: This chapter is part of Unit 1, Computational Thinking and Programming - 2, which carries 40 of the 70 theory marks together with Revision of Python Topics from Class XI, Functions, File Handling in Python and Stack.Source: CBSE Computer Science (083) syllabus 2026-27, distribution of marks, Unit 1 Computational Thinking and Programming - 2

Key concepts

Syntax errors and exceptions
NCERT section NCERT 1.2, 1.3

A syntax error breaks the rules of the language: a missing colon, an unclosed bracket, wrong indentation. Python finds it while reading the program, so not even the first line runs. An exception happens while a correct program is running, when an operation cannot be carried out: 10 / 0, int('abc'), L[10] on a short list. When an exception is not handled, Python stops the program and prints a traceback with the exception's name and message. Strictly, SyntaxError and IndentationError are also exception classes, but they are reported before execution and cannot be caught by the program that contains them.

Worked example

Classify each as a syntax error or an exception (and name it): (i) if x > 5 print(x) (ii) print(10 / 0) (iii) int('12a') (iv) a line indented without reason.

Try it first, then show the solutionSolution
  1. (i) The colon is missing: syntax error (SyntaxError), reported before running.
  2. (ii) The statement is valid but division by zero fails at run time: ZeroDivisionError.
  3. (iii) Valid statement, but '12a' is not a valid integer: ValueError at run time.
  4. (iv) Wrong indentation is caught while reading: IndentationError.

Answer: (i) and (iv) are syntax errors; (ii) ZeroDivisionError and (iii) ValueError are exceptions.

Built-in exceptions
NCERT section NCERT 1.4

Python names each kind of run-time error. The ones to know:

ExceptionRaised when
ZeroDivisionErrorthe divisor in /, // or % is zero
ValueErrorthe type is right but the value is not, e.g. int('abc')
TypeErroran operation gets the wrong type, e.g. 5 + '5'
NameErrora variable or function name is not defined
IndexErrora sequence index is out of range
KeyErrora dictionary key does not exist
IOError / FileNotFoundErrora file cannot be opened, e.g. it does not exist
ImportErrora module or name in an import cannot be found
EOFErrorinput() or a read hits end of file with no data, e.g. pickle.load() at the end of a binary file
KeyboardInterruptthe user interrupts the program (Ctrl+C)
OverflowErrora calculation is too large to represent
IndentationError, SyntaxErrorthe code breaks the language rules

Worked example

Name the exception each statement raises: (a) print(x) where x was never assigned (b) [1, 2][2] (c) {'a': 1}['b'] (d) '5' + 5 (e) float('3.5.1')

Try it first, then show the solutionSolution
  1. (a) The name x is not defined: NameError.
  2. (b) Valid indices are 0 and 1: IndexError.
  3. (c) 'b' is not a key: KeyError.
  4. (d) str and int cannot be added: TypeError.
  5. (e) A string is the right type for float() but this value is not a number: ValueError.

Answer: (a) NameError (b) IndexError (c) KeyError (d) TypeError (e) ValueError

try and except
NCERT section NCERT 1.6.2, 1.6.3

Put the statements that may fail in a try block and the response in an except block:

try:
    statements that may raise an exception
except ExceptionName:
    what to do if that exception occurs

If no exception occurs, the except block is skipped. If one occurs, the rest of the try block is skipped and Python looks for a matching except. One try can have several except blocks (checked top to bottom, and only the first match runs), an except can name a tuple of exceptions except (ValueError, TypeError):, and a bare except: (with no name) catches any exception, so it must come last. If no except matches, the exception stays unhandled and the program stops.

Worked example

Predict the output:

L = [10, 20, 30]
for i in [1, 3, 'x']:
    try:
        print(L[i] // 10)
    except IndexError:
        print('Index')
    except TypeError:
        print('Type')
    finally:
        print('Done')
Try it first, then show the solutionSolution
  1. i = 1: L[1] // 10 = 2 is printed; no exception; finally prints Done.
  2. i = 3: L[3] raises IndexError; 'Index' is printed; finally prints Done.
  3. i = 'x': a list index must be an integer, so TypeError; 'Type' is printed; then Done.

Answer: 2
Done
Index
Done
Type
Done

The finally block
NCERT section NCERT 1.7

finally comes after all the except blocks and always runs: when the try block succeeds, when an exception is handled, when an exception is not handled (finally runs, then the program stops), and even when try or except executes return. It is used for clean-up such as closing a file or a database connection. Order of blocks: try, then any except blocks, then finally. A try must be followed by at least one except or a finally.

Worked example

Predict the output:

def div(a, b):
    try:
        r = a // b
        print('A', end=' ')
    except ZeroDivisionError:
        print('B', end=' ')
        r = -1
    finally:
        print('C', end=' ')
    return r
print(div(7, 2))
print(div(7, 0))
Try it first, then show the solutionSolution
  1. div(7, 2): r = 3, prints A, no exception, finally prints C, returns 3. The outer print shows 3 on the same line.
  2. div(7, 0): 7 // 0 raises ZeroDivisionError before 'A' can print; except prints B and sets r = -1; finally prints C; returns -1.

Answer: A C 3
B C -1

finally with return
NCERT section NCERT 1.7

When the try or except block reaches return, Python first runs the finally block and only then leaves the function with the return value. So any print inside finally appears before the caller prints the returned value.

Worked example

Predict the output:

def f(x):
    try:
        return int(x) * 2
    except ValueError:
        return 0
    finally:
        print('cleanup', end=' ')
print(f('5'))
print(f('five'))
Try it first, then show the solutionSolution
  1. f('5'): the try block is about to return 10; finally runs first and prints 'cleanup '; then print shows 10.
  2. f('five'): int('five') raises ValueError; except is about to return 0; finally prints 'cleanup '; then 0 is shown.

Answer: cleanup 10
cleanup 0

Unhandled exceptions and exceptions inside except
NCERT section NCERT 1.6.3

Except blocks only guard their own try block. If an exception is raised inside an except block, the sibling except blocks of the same try do not catch it; it goes up as an unhandled exception (after any finally runs). Likewise, an exception whose type is not listed in any except is not caught. Use a general except (or except Exception:) last if every error must be caught.

Worked example

What happens when this code runs?

try:
    print(1 / 0)
except ZeroDivisionError:
    print(int('abc'))
except ValueError:
    print('inner')
Try it first, then show the solutionSolution
  1. 1 / 0 raises ZeroDivisionError, and the first except block starts.
  2. Inside it, int('abc') raises ValueError. The except ValueError below belongs to the same try, so it does not guard the except block.
  3. The ValueError is unhandled, so the program stops with a traceback; 'inner' is never printed.

Answer: Nothing is printed by the program; it stops with ValueError: invalid literal for int() with base 10: 'abc'.

Exception Handling in Python in real life

Each concept, met in an everyday situation. Read the situation, answer the question in your own words, then compare with the model answer. The one-line hook is what to remember.

Handling ValueError on input

Suppose a ticket-booking kiosk asks for the number of seats and a child types 'two' instead of 2.

Write code that converts the input to an int and, if that fails, prints 'Please enter digits' instead of crashing.

Try it first, then show the solutionSolution
  1. int() raises ValueError for text that is not a number, so wrap the conversion in try.
  2. entry = 'two'
    try:
        seats = int(entry)
        print('Booked', seats, 'seats')
    except ValueError:
        print('Please enter digits')

Answer: Please enter digits (with entry = '3' it would print Booked 3 seats). In the real kiosk, entry would come from input().

Memory hook: Right type, wrong value: ValueError.

finally for clean-up

Imagine a library app that opens the borrowers' file, reads it, and must close it whether the read works or fails.

Where should f.close() go, and why?

Try it first, then show the solutionSolution
  1. If close() is at the end of try, an exception in the read skips it and the file stays open.
  2. In finally it runs in every case: success, handled error or unhandled error.

Answer: In the finally block, because finally always runs.

Memory hook: finally = switch off the lights when you leave, whatever happened in the room.

Choosing the right except

Suppose a calculator app divides two numbers typed by the user and must show a different message for 'abc' and for 0.

Which two exceptions must it handle, and in which blocks?

Try it first, then show the solutionSolution
  1. Typing 'abc' makes float() raise ValueError.
  2. Typing 0 as the divisor makes the division raise ZeroDivisionError.
  3. Write except ValueError: and except ZeroDivisionError: as two separate handlers after one try.

Answer: ValueError ('Enter a number') and ZeroDivisionError ('Cannot divide by zero'), each in its own except block.

Memory hook: One try, one except per thing that can go wrong.

Topics in this chapter

Exception Handling in Python: syntax and key facts

Full structure
  1. 1.try: risky code
  2. 2.except Name1: handler
  3. 3.except (Name2, Name3): handler
  4. 4.except: any other
  5. 5.finally: always runs
A bare except must be the last except.
When does each block run?
No exceptiontry (whole) + finally
Handled exceptiontry (up to the error) + the first matching except + finally
Unmatched exceptiontry (up to the error) + finally, then the program stops
Only one except block ever runs for one exception.
finally and return
On return inside try or except, finally runs first, then the function returns
Output from finally appears before the caller uses the return value.
Common exception names
ZeroDivisionError, ValueError, TypeError, NameError, IndexError, KeyError, IOError / FileNotFoundError, ImportError, EOFError, KeyboardInterrupt, OverflowError
Spelling counts: 'Error' is part of every name except KeyboardInterrupt.

How the board asks Exception Handling in Python

The question patterns to expect, and the method that works for each.

Question typeHow it is askedMethod
Which block runs / predict the outputA function or loop with try-except-finally and calls that do and do not raise exceptions (1-2 marks; MCQ or output).For each call decide: exception or not, which except matches, then add finally's output; remember finally output comes before a returned value is printed.
Name the exception"Which exception is raised by..." for a statement such as int('x') or L[5] (1 mark).Ask: wrong type (TypeError), right type wrong value (ValueError), missing name (NameError), bad index (IndexError), bad key (KeyError), zero divisor (ZeroDivisionError), missing file (FileNotFoundError / IOError).
Syntax error versus exceptionDifferentiate with examples (2 marks).Syntax error: detected before running, code violates the grammar. Exception: detected during running, code is valid but an operation fails. Give one line of each.
Add exception handling to a programRewrite a division or input program so it does not crash on bad input (2-3 marks), or inside file and SQL programs.Wrap only the risky lines in try; write a specific except for each expected exception and a finally for clean-up.
Assertion-reason on finally and except orderStatements such as "finally runs even if an exception is not handled" or "a bare except must come last".Check each claim against the four flow rules in the key facts.

Tricks to remember Exception Handling in Python

Short memory aids. Say each one aloud once, then use it on a question the same day.

  • T-E-F: Try, Except, Finally

    "Try Eating Fruit": the blocks always appear in this order.

    Use it when: Writing the structure and spotting wrongly ordered blocks.

  • finally never misses

    No error, handled error, unhandled error, return: finally runs in all four.

    Use it when: Which-block-runs MCQs.

  • Type versus Value

    Wrong kind of thing = TypeError ('5' + 5). Right kind, wrong content = ValueError (int('5a')).

    Use it when: Naming the exception.

  • First match wins

    Except blocks are checked top to bottom, and only the first matching one runs; a bare except at the top would swallow everything, so Python requires it last.

    Use it when: Order-of-except questions.

Exception Handling in Python: board-level solved questions

Ordered from board level to HOTS. Cover the solution, write your own, then compare step by step.

Example 1: Three calls, one finally · 2 marks · Short answerHarder board level

Predict the output:

def test(a, b):
    try:
        print(a / b, end=' ')
    except ZeroDivisionError:
        print('Zero', end=' ')
    except TypeError:
        print('Type', end=' ')
    finally:
        print('#')
test(6, 3)
test(6, 0)
test('6', 3)
Try it first, then show the solutionSolution
  1. test(6, 3): 6 / 3 = 2.0 is printed, then finally prints #.
  2. test(6, 0): ZeroDivisionError, so 'Zero', then #.
  3. test('6', 3): str / int is a TypeError, so 'Type', then #.

Answer: 2.0 #
Zero #
Type #

Example 2: Exception inside a handler · 1 mark · MCQHOTS / competency

What is the result of running this code?

try:
    print(1 / 0)
except ZeroDivisionError:
    print(int('abc'))
except ValueError:
    print('inner')

(a) inner (b) 0 (c) The program stops with ValueError (d) The program stops with ZeroDivisionError

Try it first, then show the solutionSolution
  1. ZeroDivisionError is caught by the first except.
  2. int('abc') inside that handler raises ValueError, which the sibling except ValueError does not guard.
  3. So the ValueError is unhandled.

Answer: (c) The program stops with ValueError

Example 3: Safe input loop · 3 marks · Short answerHarder board level

Given the list entries = ['12', 'x', '0', '5'] (as if typed by a user), write code that tries to compute 60 // value for each entry, printing the result, 'not a number' or 'zero not allowed', and 'next' after every entry.

Try it first, then show the solutionSolution
  1. Two different exceptions are possible: ValueError from int() and ZeroDivisionError from //.
  2. entries = ['12', 'x', '0', '5']
    for e in entries:
        try:
            v = int(e)
            print(60 // v)
        except ValueError:
            print('not a number')
        except ZeroDivisionError:
            print('zero not allowed')
        finally:
            print('next')
  3. '12' gives 5; 'x' gives ValueError; '0' gives ZeroDivisionError; '5' gives 12.

Answer: 5
next
not a number
next
zero not allowed
next
12
next

Example 4: Assertion-reason on finally · 1 mark · Assertion-reasonHOTS / competency

Assertion (A): In a function, a print() in the finally block runs even when the try block executes a return statement.
Reason (R): The finally block is executed only when an exception occurs in the try block.
(a) Both true, R explains A (b) Both true, R does not explain A (c) A true, R false (d) A false, R true

Try it first, then show the solutionSolution
  1. A is true: finally runs before the function actually returns.
  2. R is false: finally runs whether or not an exception occurs.

Answer: (c) A is true but R is false.

Example 5: Order of except blocks · 2 marks · Short answerHarder board level

Predict the output:

D = {'a': 10}
for k in ['a', 'b']:
    try:
        print(D[k] / (len(k) - 1))
    except KeyError:
        print('missing', k)
    except Exception:
        print('other error')
Try it first, then show the solutionSolution
  1. k = 'a': D['a'] exists, but len('a') - 1 = 0, so ZeroDivisionError. It is not a KeyError; except Exception catches it: 'other error'.
  2. k = 'b': D['b'] raises KeyError before the division is reached: 'missing b'.

Answer: other error
missing b

Example 6: Name the exception · 1 mark · MCQBoard level

Which exception is raised by x = 5 + '5'? (a) ValueError (b) TypeError (c) SyntaxError (d) NameError

Try it first, then show the solutionSolution
  1. The statement is syntactically correct, so it is not a SyntaxError.
  2. + cannot combine an int and a str: the types are wrong.

Answer: (b) TypeError

Example 7: Which lines run? · 2 marks · Short answerHarder board level

Predict the output:

L = [5, 0, 'a']
total = 0
for x in L:
    try:
        total += 10 // x
        print('ok', total)
    except ZeroDivisionError:
        total += 1
    except:
        total += 100
print(total)
Try it first, then show the solutionSolution
  1. x = 5: total = 2, prints ok 2.
  2. x = 0: ZeroDivisionError; total = 3 (nothing printed).
  3. x = 'a': int // str is a TypeError; caught by the bare except; total = 103.
  4. After the loop, 103 is printed.

Answer: ok 2
103

Case-study practice (Section E style)

Read the situation, then answer every part. In the board paper this is a 4-mark question split into 1 + 1 + 2 marks.

Fee calculator in the school office

Suppose the school office uses this function to work out the monthly fee from the annual fee typed by a clerk:

def monthly(fee_text, months):
    try:
        fee = int(fee_text)
        result = fee // months
    except ValueError:
        result = 'Invalid fee'
    except ZeroDivisionError:
        result = 'Months cannot be 0'
    finally:
        print('Calculation attempted')
    return result
  1. (i) · 1 mark

    What does monthly('24000', 12) return?

    Answer

    Answer: 2000

    24000 // 12 = 2000; 'Calculation attempted' is printed before the value is returned.

  2. (ii) · 1 mark

    Which exception is handled when the clerk types '24,000'?

    Answer

    Answer: ValueError

    int() cannot convert text containing a comma.

  3. (iii) · 2 marks

    Give the complete output of print(monthly('6000', 0)) and explain the order of the lines.

    Answer

    Answer: Calculation attempted
    Months cannot be 0

    6000 // 0 raises ZeroDivisionError; the handler sets result; finally prints its line; only then does the function return and print() display the message.

Where the marks are

How a typical answer is split into step marks. Show every step: a right final answer alone rarely earns full marks.

Differentiate between a syntax error and an exception with one example of each. [2 marks] (2 marks)

StepMarks
Syntax error: violates the rules of Python and is detected before execution, e.g. if a > b print(a) (missing colon)1
Exception: an error during execution of valid code, e.g. print(5 / 0) raises ZeroDivisionError1

Write a program that reads two numbers and prints their quotient, handling non-numeric input and division by zero with suitable messages, and always printing 'End'. [3 marks] (3 marks)

StepMarks
Reading and converting inside try, and the division1
Separate except blocks for ValueError and ZeroDivisionError with messages1
finally block printing 'End'1

Predict the output of the div() program with calls div(7, 2) and div(7, 0), and explain the role of each block. [4 marks] (4 marks)

StepMarks
Output A C 31
Output B C -11
try: holds the division; skipped after the error0.5
except: handles ZeroDivisionError and sets r0.5
finally: runs in both calls before return1

Write a function SAFE_AVG(L) that returns the average of the numbers in L. It must return 0 if L is empty, return None if L holds a non-number, and print 'checked' every time. Show three calls. [5 marks] (5 marks)

StepMarks
Header and the average computed inside try1
except ZeroDivisionError returning 01
except TypeError returning None1
finally printing 'checked'1
Three calls with the correct outputs1

Where students lose marks in Exception Handling in Python

The slips examiners see most often, and what to write instead.

  • Mistake: Forgetting the finally output when a function returns

    Students print the return value first because return looks like the last word.

    Wrong working

    print(f('5')) gives
    10
    cleanup

    Right working

    print(f('5')) gives
    cleanup 10

    Do this: When try or except returns, run finally first, then hand the value back to the caller.

    Usually costs: 1 mark

  • Mistake: Assuming the rest of the try block runs after an exception

    Control jumps straight to the matching except as soon as the error happens.

    Wrong working

    r = 7 // 0 raises the error, then print('A') still runs

    Right working

    print('A') is skipped; control goes to except ZeroDivisionError

    Do this: Draw a line under the statement that raises the exception: nothing below it in the try block runs.

    Usually costs: 1 mark

  • Mistake: Confusing syntax errors with exceptions

    Both show red error messages, but a syntax error stops the program before any line runs.

    Do this: In a definition answer write 'detected before execution' for syntax errors and 'detected during execution' for exceptions, with one example each.

    Usually costs: 1 mark in a 2-mark difference question

  • Mistake: Misspelling exception names

    Names such as ZeroDivisonError or IndexErrors are not valid, so the except would not match (and the answer is marked wrong).

    Do this: Learn the exact names: ZeroDivisionError, ValueError, TypeError, NameError, IndexError, KeyError, EOFError, IOError, ImportError.

    Usually costs: Half to 1 mark

  • Mistake: Thinking an except block also guards the other except blocks

    An exception raised inside a handler is not caught by its sibling handlers.

    Do this: If code inside an except can fail, put it in its own nested try.

    Usually costs: 1 mark in an output or assertion question

NCERT exercise guide: Exception Handling in Python

What each exercise in the NCERT chapter tests, how to approach it, and a question of the same kind solved step by step. Questions here are written in our own words.

NCERT Chapter 1 exercises: theory questions

What it tests: Syntax errors versus exceptions, the meaning of built-in exceptions, and when each block runs.

How to approach it: Answer in two parts: a one-line definition and a one-line code example.

Same kind as the 'name the exception' exercise

Which built-in exception is raised in each case? (a) a module name in an import is misspelt (b) the user presses Ctrl+C while the program waits for input (c) a = [1, 2]; a[5] = 3

Show the solutionSolution
  1. (a) The module cannot be found: ImportError (ModuleNotFoundError is its subclass).
  2. (b) The user interrupted the program: KeyboardInterrupt.
  3. (c) Assigning to a non-existent index: IndexError.

Answer: (a) ImportError (b) KeyboardInterrupt (c) IndexError

NCERT Chapter 1 exercises: programs with try-except-finally

What it tests: Adding handlers to a program that divides, converts input or indexes a list.

How to approach it: Identify every line that can fail, name its exception, and add one except per exception plus finally for clean-up.

Same kind as the division exercise

Write SAFE_AVG(L) as described: return the average, 0 for an empty list, None if a non-number is present, and print 'checked' every time.

Show the solutionSolution
  1. def SAFE_AVG(L):
        try:
            return sum(L) / len(L)
        except ZeroDivisionError:
            return 0
        except TypeError:
            return None
        finally:
            print('checked')
    print(SAFE_AVG([4, 6]))
    print(SAFE_AVG([]))
    print(SAFE_AVG([4, 'a']))
  2. sum([]) / len([]) is 0 / 0: ZeroDivisionError. sum([4, 'a']) adds int and str: TypeError.
  3. Each call prints 'checked' before its value is printed.

Answer: checked
5.0
checked
0
checked
None

Practice questions on Exception Handling in Python

Write each answer on paper first. Open the hint only if you are stuck, and the answer only when you have finished.

  1. Q1 · 1 mark · MCQBoard level

    Which of these is detected before a program starts running? (a) ZeroDivisionError (b) IndexError (c) SyntaxError (d) ValueError

    Hint

    Only grammar errors are found while reading the code.

    Answer

    (c) SyntaxError

  2. Q2 · 1 mark · Very short answerBoard level

    Name the exception raised by: (a) L = [1, 2, 3]; print(L[3]) (b) import maths (c) print(Total) when Total is not defined.

    Hint

    One each: index, import, name.

    Answer

    (a) IndexError (b) ImportError (ModuleNotFoundError) (c) NameError

  3. Q3 · 2 marks · Short answerHOTS / competency

    Predict the output:

    def g(n):
        try:
            return 10 // n
        except ZeroDivisionError:
            return 'inf'
        finally:
            print('F', end='')
    print(g(2), g(0))
    Hint

    Both calls finish (printing F) before print() shows anything.

    Answer

    FF5 inf

  4. Q4 · 2 marks · Short answerBoard level

    Rewrite the code so that it prints 'Invalid' instead of crashing when the text is not a number, and always prints 'Bye':

    n = int(text)
    print(n * 2)
    Hint

    One except for ValueError and a finally.

    Answer
    text = '4a'
    try:
        n = int(text)
        print(n * 2)
    except ValueError:
        print('Invalid')
    finally:
        print('Bye')

    Output for '4a': Invalid, then Bye.

  5. Q5 · 1 mark · Assertion-reasonHOTS / competency

    Assertion (A): A try block can be followed directly by a finally block without any except block.
    Reason (R): Every try block must have at least one except block.

    Hint

    try needs at least one except or a finally.

    Answer

    (c) A is true but R is false.

  6. Q6 · 2 marks · Short answerHarder board level

    Predict the output:

    values = ['3', '', '4']
    for v in values:
        try:
            print(10 / int(v))
        except (ValueError, ZeroDivisionError):
            print('skip')
    Hint

    int('') is not a valid number.

    Answer

    3.3333333333333335
    skip
    2.5

  7. Q7 · 3 marks · Short answerHarder board level

    Write a function GET_ITEM(L, i) that returns L[i], or the string 'No item' if i is out of range, or 'Bad index' if i is not an integer. Show calls for L = [4, 8], i = 1, 5 and 'a'.

    Hint

    IndexError and TypeError.

    Answer
    def GET_ITEM(L, i):
        try:
            return L[i]
        except IndexError:
            return 'No item'
        except TypeError:
            return 'Bad index'
    L = [4, 8]
    print(GET_ITEM(L, 1), GET_ITEM(L, 5), GET_ITEM(L, 'a'))

    Output: 8 No item Bad index

  8. Q8 · 2 marks · Short answerHarder board level

    Explain why the order of these except blocks is wrong, and correct it:

    try:
        x = int(input())
    except:
        print('Error')
    except ValueError:
        print('Not a number')
    Hint

    A bare except catches everything.

    Answer

    A bare except catches every exception, so a later named except could never run; Python reports a SyntaxError ('default except: must be last'). Put except ValueError: first and the bare except: last.

  9. Q9 · 2 marks · Short answerHarder board level

    Predict the output:

    try:
        d = {'x': 1}
        print(d['x'])
        print(d['y'])
        print('end of try')
    except KeyError:
        print('key missing')
    finally:
        print('finally')
    Hint

    The second lookup fails.

    Answer

    1
    key missing
    finally

Test your recall

Answer in your head or on paper first, then open the card. Pulling an answer out of memory makes it stick far better than re-reading.

  1. 1.When is a syntax error detected?Show answer

    Before the program runs, when Python reads (parses) the code.

  2. 2.Which exception does int('3.5') raise?Show answer

    ValueError.

  3. 3.Which exception is raised when you open a file that does not exist in read mode?Show answer

    FileNotFoundError (a kind of IOError / OSError).

  4. 4.Can a try block exist without except?Show answer

    Yes, if it has a finally block. A try needs at least one except or a finally.

  5. 5.How many except blocks run for one exception?Show answer

    Only one: the first one that matches.

  6. 6.Does finally run if the exception is not handled?Show answer

    Yes. finally runs, and then the program stops with the traceback.

  7. 7.Which exception does pickle.load() raise at the end of a binary file?Show answer

    EOFError.

  8. 8.Where must a bare except: be placed?Show answer

    After all the named except blocks (it must be last).

Best order to study it

  1. Syntax errors versus exceptions, with an example of each.
  2. The built-in exceptions table: what raises each one.
  3. try with one except, then several except blocks and the bare except.
  4. finally: the four cases in which it runs, then finally with return.
  5. Exceptions inside except blocks and unhandled exceptions.
  6. Practise output questions mixing loops, functions and try-except-finally.

Quick revision checklist

The night before the exam: can you do each of these without looking?

  • Syntax error: found before running. Exception: raised while running.
  • An unhandled exception stops the program with a traceback.
  • try holds risky code; at the first exception the rest of try is skipped.
  • Except blocks are checked top to bottom; only the first match runs; a bare except goes last.
  • If no except matches, finally runs and then the program stops.
  • finally always runs, even when try or except returns.
  • ValueError = right type, wrong value; TypeError = wrong type.
  • ZeroDivisionError, IndexError, KeyError, NameError, FileNotFoundError / IOError, EOFError, ImportError, KeyboardInterrupt, OverflowError.

Exception Handling in Python: frequently asked questions

Are raise and assert in the CBSE Class 12 Computer Science syllabus for 2026-27?

No. The syllabus names only "handling exceptions using try-except-finally blocks". NCERT section 1.5 on raise and assert is not named, so it is not taught or tested on this page.

Is the else clause with try in the syllabus?

The syllabus names try, except and finally. NCERT also shows an else block that runs when no exception occurs; it is good to recognise, but questions based on the syllabus use try-except-finally.

Why is exception handling used with files and databases?

Opening a file or connecting to a database can fail at run time. A try block lets the program show a message instead of crashing, and finally makes sure the file or connection is closed.

What is the difference between ValueError and TypeError?

TypeError: the operation gets an object of the wrong type, such as adding a string to a number. ValueError: the type is acceptable but the value is not, such as int('abc').

How many marks is exception handling worth?

No separate figure is given. It is part of Unit 1 (40 of 70 theory marks), mostly as 1-mark MCQs or assertion-reason items and 2-mark output or theory questions.

Based on: CBSE Computer Science (083) syllabus 2026-27; NCERT Computer Science, Textbook for Class XII (Reprint 2026-27)