Skip to content
Computer ScienceCBSE Class 12 · Exception Handling in Python

try and except Blocks: Handling Exceptions in Python (Class 12 Computer Science)

Updated 16 October 2026 · Fact-checked

Code that might fail is placed in a try block. If an exception occurs, Python skips the rest of the try block and runs the first except block that names that exception, then continues after the whole statement. If no except block matches, the exception is passed to the caller, and the program stops if nothing handles it.

Understand try and except Blocks

Errors and exceptions. A syntax error (such as a missing colon) is found when Python parses the program, so nothing runs until it is fixed. An exception happens while a correct-looking program runs: dividing by zero, converting 'abc' to int, using a missing index or key (NCERT 1.2, 1.3). Unless it is handled, an exception stops the program with a traceback.

Throwing and catching (NCERT 1.6.2). When an error occurs, Python creates an exception object holding its type and position. Creating it and handing it to the runtime system is called throwing (raising) the exception. The runtime system looks for a handler: first in the function where the error happened, then in the function that called it, and so on back through the call stack. Running a suitable handler is catching the exception. If none is found, the program stops.

The try...except statement (NCERT 1.6.3):

try:
    statements that may raise an exception
except ExceptionName:
    statements run only if that exception occurs
  • If the try block finishes without an error, every except block is skipped.
  • If an exception occurs, the rest of the try block is abandoned at once, and Python checks the except clauses from top to bottom; the first one that matches runs. Afterwards execution continues with the statement after the whole try...except, not back in the try block.
  • One try can have several except clauses, one per expected exception (NCERT Program 1-3 handles ZeroDivisionError and ValueError).
  • An except clause with no exception name catches anything not caught above; it must be the last clause, otherwise Python reports a SyntaxError.
  • If the exception does not match any clause, it is not handled here: it travels to the caller, and if the caller does not handle it either, the program stops with a traceback.

NCERT also shows an optional else clause (1.6.4), which runs only when the try block raised nothing. The CBSE 2026-27 syllabus names 'handling exceptions using try-except-finally blocks'; raise and assert are not in the syllabus.

Typical board items: predict the output when one item of a loop raises an exception, choose which block runs, write a program that keeps asking for input until a valid integer is entered, or explain the difference between a syntax error and an exception.

try and except Blocks: key facts

Key terms
Syntax errordetected before the program runs
Exceptionerror detected while the program runs
Throwing (raising)creating the exception object and passing it to the runtime system
Catchingrunning the handler that matches
Call stacklist of functions searched for a handler, from the current one back to the main program
NCERT Class XII Computer Science 1.2, 1.3 and 1.6.2.
What runs when
No exception in trywhole try runs; all except blocks skipped
Exception in tryrest of try skipped → first matching except runs → continue after the statement
No matching exceptexception passed to the caller; program stops if unhandled
Control never goes back into the try block.
Clause order
  1. 1.try
  2. 2.except Specific1
  3. 3.except Specific2
  4. 4.except (no name, last)
  5. 5.else (optional)
  6. 6.finally (optional, last)
A bare except placed before others is a SyntaxError.
Input-validation pattern
  1. 1.while True:
  2. 2.try: n = int(input())
  3. 3.break
  4. 4.except ValueError: print a message and loop again
The loop ends only when int() succeeds.

How to answer try and except Blocks questions

To predict the output of code with try and except, trace it statement by statement.

  1. 1Run the try block line by line and write each output as it happens.
  2. 2At the first line that raises an exception, stop the try block. Name the exception (ZeroDivisionError, ValueError, IndexError, KeyError, TypeError, NameError ...).
  3. 3Check the except clauses from top to bottom; run only the first one that matches (a bare except matches anything).
  4. 4If none matches, the exception leaves this try: look for a handler in the caller; if there is none, the program stops and no later line prints.
  5. 5After the except block, continue with the first statement after the whole try...except, or with the next loop pass if it is inside a loop.
  6. 6When the code is inside a function called in a print(), finish all the calls (and their prints) before the outer print shows the returned values.
  7. 7In programs you write, name specific exceptions where you can and keep only the risky statements inside try.

try and except Blocks in real life

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

Re-asking until the input is valid

Suppose a railway kiosk asks for the passenger's age to decide the fare (₹50 below 12, otherwise ₹100), and a passenger first types 'ten' and then 9.

Write code that keeps asking until an integer is entered and then shows the fare. What appears on the screen?

Try it first, then show the solutionSolution
  1. int('ten') raises ValueError, so the except block prints a message and the loop asks again; int('9') works and break leaves the loop.
  2. while True:
        try:
            age = int(input('Age: '))
            break
        except ValueError:
            print('Enter digits only')
    if age < 12:
        print('Fare: 50')
    else:
        print('Fare: 100')
  3. On the screen, what the passenger types appears after the prompt 'Age: ', and pressing Enter moves to a new line, so the message and the fare start on lines of their own.

Answer: Age: ten
Enter digits only
Age: 9
Fare: 50

Memory hook: The try is a polite clerk: on a wrong answer, explain and ask again instead of shutting the counter.

Skipping bad records instead of crashing

Imagine a shop's sales sheet arrives as text values ['120', '85', 'N/A', '40'], where 'N/A' marks a day the shop was shut.

Add up the valid sales and count the bad entries without the program stopping.

Try it first, then show the solutionSolution
  1. Put only the risky conversion inside try; ValueError for 'N/A' is counted and the loop goes on.
  2. sales = ['120', '85', 'N/A', '40']
    total = bad = 0
    for s in sales:
        try:
            total += int(s)
        except ValueError:
            bad += 1
    print(total, bad)

Answer: 245 1

Memory hook: One torn page should not stop you reading the whole register.

Tricks to remember try and except Blocks

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

  • Try, trip, jump

    Python tries each line; on the first trip it jumps out of try to the matching except and never comes back.

    Use it when: Tracing output when an exception occurs mid-block.

  • First match wins

    except clauses are checked like a queue at a counter: the first one that fits serves the exception.

    Use it when: Multiple except clauses.

  • Catch-all comes last

    The bare except is the goalkeeper: it stands at the back, after all the specific defenders.

    Use it when: Order of except clauses.

  • Syntax before, exception during

    Syntax errors stop the program before it starts; exceptions stop it while it is running.

    Use it when: Distinguishing the two in 1-2 mark questions.

try and except Blocks: solved examples

Ordered from board level to HOTS. Try each one before you open the solution.

Example 1: The rest of try is skipped · 1 mark · Very short answerBoard level

Write the output:

try:
    x = int('12a')
    print('converted')
except ValueError:
    print('bad number')
print('end')
Try it first, then show the solutionSolution
  1. int('12a') raises ValueError, so print('converted') never runs.
  2. The matching except prints 'bad number'; then the statement after the block prints 'end'.

Answer: bad number
end

Example 2: Multiple except clauses inside a function · 2 marks · Short answerHarder board level

Predict the output:

def safe_div(a, b):
    try:
        q = a / b
        print('ok', end=' ')
        return q
    except ZeroDivisionError:
        print('zero', end=' ')
        return 0
    except TypeError:
        print('type', end=' ')
        return -1
print(safe_div(9, 3), safe_div(5, 0), safe_div('5', 2))
Try it first, then show the solutionSolution
  1. The three calls run (left to right) before print shows anything: 9 / 3 works ('ok', returns 3.0); 5 / 0 raises ZeroDivisionError ('zero', returns 0); '5' / 2 raises TypeError ('type', returns -1). (1 mark)
  2. Then print shows the three returned values on the same line. (1 mark)

Answer: ok zero type 3.0 0 -1

Example 3: Summing the valid numbers · 3 marks · Short answerHarder board level

data = ['12', 'x', '7', '3.5', '-4']. Write a program that adds up the items that int() can convert and counts the ones it cannot. Give the output.

Try it first, then show the solutionSolution
  1. Loop over the list with the conversion inside try (1 mark); add in try, count in except ValueError (1 mark); print both (1 mark).
  2. data = ['12', 'x', '7', '3.5', '-4']
    s = bad = 0
    for d in data:
        try:
            s += int(d)
        except ValueError:
            bad += 1
    print('Sum:', s, 'Invalid:', bad)
  3. int('3.5') also raises ValueError (int() of a string accepts only whole numbers), so 'x' and '3.5' are invalid: 12 + 7 - 4 = 15.

Answer: Sum: 15 Invalid: 2

Example 4: Handled in the caller · 2 marks · Short answerHarder board level

Predict the output and say where the exception is caught:

def get(L, i):
    print('fetching', i)
    return L[i]
try:
    print(get([1, 2], 1))
    print(get([1, 2], 5))
    print('after')
except IndexError:
    print('caught in caller')
Try it first, then show the solutionSolution
  1. get(..., 1) prints 'fetching 1' and returns 2, which is printed. (½ mark)
  2. get(..., 5) prints 'fetching 5'; L[5] raises IndexError. get has no handler, so the runtime system searches its caller (the call stack). (1 mark)
  3. The caller's except IndexError catches it; 'after' is skipped. (½ mark)

Answer: fetching 1
2
fetching 5
caught in caller

Example 5: Specific and generic handlers in a loop · 2 marks · Short answerHOTS / competency

Predict the output:

for v in ['4', 'zero', '0']:
    try:
        print(10 // int(v))
    except ZeroDivisionError:
        print('div by 0')
    except:
        print('other')
Try it first, then show the solutionSolution
  1. '4': 10 // 4 = 2. (½ mark)
  2. 'zero': int() raises ValueError; it is not ZeroDivisionError, so the bare except prints 'other'. (1 mark)
  3. '0': 10 // 0 raises ZeroDivisionError, caught by the first clause. (½ mark)

Answer: 2
other
div by 0

Example 6: Case study: a marks-entry program · 4 marks · Case-basedHOTS / competency

Suppose a teacher's program reads marks from a dictionary M = {'Asha': '78', 'Ravi': 'AB', 'Joy': '91'} ('AB' means absent) and must print the average of the numeric marks, then look up a roll call name typed by mistake as 'Jai'.
(i) Which exception does int('AB') raise, and which does M['Jai'] raise? (1 mark)
(ii) Write the code so that neither stops the program. (2 marks)
(iii) Why should the bare except not be the first clause? (1 mark)

Try it first, then show the solutionSolution
  1. (i) int('AB') raises ValueError; M['Jai'] raises KeyError.
  2. (ii)
    M = {'Asha': '78', 'Ravi': 'AB', 'Joy': '91'}
    vals = []
    for name in M:
        try:
            vals.append(int(M[name]))
        except ValueError:
            print(name, 'absent')
    print('Average:', sum(vals) / len(vals))
    try:
        print(M['Jai'])
    except KeyError:
        print('No such student')
  3. Ravi is reported absent; the average of 78 and 91 is 84.5; the wrong name is handled by except KeyError.
  4. (iii) A bare except catches every exception, so later specific clauses could never run; Python therefore insists that it be last (otherwise SyntaxError).

Answer: (i) ValueError; KeyError (ii) Output: Ravi absent / Average: 84.5 / No such student (iii) It would hide the specific handlers; Python requires it to be last.

Where students lose marks in try and except Blocks

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

  • Mistake: Printing the lines after the error inside try

    Once an exception occurs, the rest of the try block is skipped.

    Wrong working

    bad number
    converted
    end

    Right working

    bad number
    end

    Do this: Stop the try block at the failing line.

    Usually costs: 1 mark.

  • Mistake: Assuming any except catches any exception

    A named clause catches only that exception; others pass on and may stop the program.

    Wrong working

    except IndexError catches d['b'] → prints 'index'

    Right working

    d['b'] raises KeyError, which except IndexError does not catch

    Do this: Name the exception the faulty line really raises before matching clauses.

    Usually costs: 1 mark.

  • Mistake: Putting the bare except first

    Python requires the default except to be the last clause.

    Wrong working

    except:
    ...
    except ValueError:
    ...

    Right working

    except ValueError:
    ...
    except:
    ...

    Do this: Specific clauses first, catch-all last.

    Usually costs: Half to 1 mark.

  • Mistake: Wrapping the whole program in one try

    One error then skips everything after it, and examiners expect the handler around the risky statement.

    Do this: Keep only the conversion, division or lookup inside try, especially inside loops.

    Usually costs: Half a mark in 3-mark programs.

Exam tips

  • Learn the exact names: ZeroDivisionError, ValueError, TypeError, IndexError, KeyError, NameError; misspelt names cost the mark.
  • In a 'write a program' answer, show at least one specific except clause; a bare except alone looks careless.
  • When asked for the difference between a syntax error and an exception, give one example of each (a missing colon; 10 / 0).
  • Put input conversion (int(input())) inside try when the question says 'handle invalid input'.
  • raise and assert are not in the 2026-27 syllabus; questions are about try, except and finally.

Practice questions on try and except Blocks

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

    In Python, the statements that may raise an exception are written in the:
    (a) except block (b) try block (c) finally block (d) else block

    Hint

    You try the risky part.

    Answer

    (b) try block

  2. Q2 · 1 mark · MCQBoard level

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

    Hint

    Parsing happens first.

    Answer

    (c) SyntaxError

  3. Q3 · 1 mark · Very short answerBoard level

    Write the output:

    try:
        print(int('7') + 1)
    except ValueError:
        print('V')
    print('next')
    Hint

    Does anything fail?

    Answer

    8
    next

  4. Q4 · 2 marks · Short answerHarder board level

    Write the output:

    L = [5, 0, 2]
    for x in L:
        try:
            print(10 / x, end=' ')
        except ZeroDivisionError:
            print('inf', end=' ')
    Hint

    The loop continues after the except block.

    Answer

    2.0 inf 5.0

  5. Q5 · 2 marks · Short answerHarder board level

    Write a function to_int(s) that returns int(s), or None if s cannot be converted. Show print(to_int('25'), to_int('2 5'), to_int('-8')).

    Hint

    Return inside try, return None inside except.

    Answer
    def to_int(s):
        try:
            return int(s)
        except ValueError:
            return None
    print(to_int('25'), to_int('2 5'), to_int('-8'))

    Output: 25 None -8

  6. Q6 · 1 mark · Assertion-reasonHarder board level

    Assertion (A): When an exception occurs in a try block, the remaining statements of the try block are not executed.
    Reason (R): Control jumps to the matching except block.
    (a) Both A and R are true and R is the correct explanation of A. (b) Both A and R are true but R is not the correct explanation of A. (c) A is true but R is false. (d) A is false but R is true.

    Hint

    Try, trip, jump.

    Answer

    (a) Both are true and R explains A.

  7. Q7 · 2 marks · Short answerHOTS / competency

    What does this code display? Explain.

    try:
        d = {'a': 1}
        print(d['b'])
    except IndexError:
        print('index')
    print('done')
    Hint

    Which exception does a missing key raise?

    Answer

    Nothing is printed by the program itself: d['b'] raises KeyError, which does not match except IndexError and has no other handler, so the program stops with KeyError: 'b' and 'done' is never printed.

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.What is throwing an exception?Show answer

    Creating the exception object and handing it to the runtime system to find a handler.

  2. 2.What is catching an exception?Show answer

    Executing the handler (except block) that matches it.

  3. 3.Where must a bare except clause be placed?Show answer

    After all the other except clauses.

  4. 4.After an except block runs, where does execution continue?Show answer

    At the statement after the whole try...except, not in the try block.

  5. 5.What happens if no except clause matches?Show answer

    The exception goes to the caller; if no handler is found anywhere, the program stops.

  6. 6.What does int('3.5') raise?Show answer

    ValueError.

try and except Blocks: frequently asked questions

What is the difference between a syntax error and an exception?

A syntax error breaks the rules of Python, such as a missing colon, and is reported before the program runs. An exception occurs while the program runs, such as dividing by zero; it can be handled with try and except.

Can one try block have more than one except block?

Yes. Each except names an exception to handle. Python checks them from top to bottom and runs only the first one that matches. A clause with no exception name can be added last to catch anything else.

Is the else clause in the CBSE syllabus?

The 2026-27 syllabus names try-except-finally. NCERT explains the optional else clause (1.6.4), which runs only when the try block raises nothing, so it is useful to know, but board questions centre on try, except and finally.

What is the call stack in exception handling?

It is the chain of functions that were called to reach the failing line. Python searches it backwards, from the current function to its caller and so on, for a matching handler; if none is found, the program stops.