CBSE Class 12 · Computer Science 083 · Exception handling 2026-27

Exception handling class 12 computer science: try, except, finally, with questions.

This is one of the shortest chapters in 083, and it can be finished in an afternoon if you keep to two questions. Which exception does this statement raise? Which blocks run because of it? The notes below answer both with tables, then use them in six programs a Class 12 student really writes: checking typed input, reading a missing file, reaching the end of a binary file. Nineteen practice questions close the page.

Live one to one · messages copied from Python, not from memory · your errors used as the examples

Start here

Courses that take this chapter further

Handlers make sense only inside real programs, so each of these puts them to work: in board answers, in Python projects, or in a program that talks to a database.

Ans. The short version

Exception handling in class 12 computer science (CBSE 083, 2026-27) means dealing with errors that appear while a program is running, using try, except and finally. Risky statements go in try; the except block that names the raised exception runs; finally runs either way. If no except matches, finally still runs and the program then stops with the error. Modern Age Coders teaches it live, personalised one to one, at your own days and timing, inside the file programs where it is examined. A priority demo gives you one full class to judge first.

Q1. What is an exception?

Exception handling in Python Class 12 notes: errors and exceptions

An exception is an error that Python meets while a program is running, such as dividing by zero or opening a file that is not there. Handling it means writing code that deals with the problem so the program need not stop.

Kind of mistakeWhen it showsExampleCan try-except help?
Syntax errorBefore any line runsA missing colon after ifNo. The program never starts, so its try never runs
Exception (run-time error)While running, at one statementint("twelve")Yes, if that statement is inside a try
Logical errorNever reported. The answer is wrongtotal = marks * 3 where + was meantNo. Python sees nothing wrong

Nine built-in exceptions, and what sets each one off

Learn the left column by running the middle one. The last column is the message Python 3.14 printed for us; your lab version may word it a little differently, and the exam wants the name.

ExceptionA statement that raises itMessage
ZeroDivisionError60 / 0division by zero
ValueErrorint("twelve")invalid literal for int() with base 10: 'twelve'
TypeError"Rs " + 50can only concatenate str (not "int") to str
NameErrorprint(totl)name 'totl' is not defined
IndexError[4, 7][2]list index out of range
KeyError{"tea": 10}["milk"]'milk'
FileNotFoundErroropen("gone.txt")[Errno 2] No such file or directory: 'gone.txt'
EOFErrorpickle.load(f) with no record leftRan out of input
ModuleNotFoundErrorimport mathsNo module named 'maths'

ValueError or TypeError? Ask whether the type was acceptable. int("twelve") was given a string, which int() accepts, but this string's value will not convert: ValueError. len(5) was given a number, which len() never accepts: TypeError.

Q2. Which block runs?

How does try, except, finally work in Class 12?

Python runs try until a statement fails, jumps at once to the first except that names that exception, and runs finally on the way out in every case. The rest of the try block is skipped and is not resumed.

Five letters, three pathstanks.py
def fill(litres, tanks):
    try:
        print("A", end=" ")
        each = litres // int(tanks)
        print("B", end=" ")
    except ZeroDivisionError:
        print("C", end=" ")
    finally:
        print("D", end=" ")
    print("E")

fill(90, "3")
fill(90, "0")
fill(90, "x")

Output

A B D E
A C D E
A D
ValueError: invalid literal for int() with base 10: 'x'

Only the last line of the error report is shown. The third call has no matching except, so E never prints.

Read it as five steps

  1. Enter try

    Statements run in order, as usual.

  2. Something fails

    The remaining try statements are dropped. That is why B is missing in the second call.

  3. Look for a match

    The except clauses are checked from the top, and at most one of them runs.

  4. Run finally

    With a failure or without, matched or not.

  5. Go on, or stop

    If the exception was handled, or never happened, the lines below continue. If not, the program ends with the error.

Five situations in one table

SituationtryexceptfinallyStatements below
No exceptionRuns fullySkippedRunsRun
Exception with a matching exceptRuns up to the failureRunsRunsRun
Exception with no matching exceptRuns up to the failureSkippedRunsNot run, program stops
The except block itself failsRuns up to the failureRuns up to its own failureRunsNot run, program stops
return inside tryRuns up to the returnSkippedRuns, then the value goes backNot run, function has ended
return meets finallycheck.py
def check(n):
    try:
        return 100 // n
    except ZeroDivisionError:
        return -1
    finally:
        print("checked", n)

print(check(8))
print(check(0))

Output

checked 8
12
checked 0
-1

Rules for writing the blocks

  • A try needs at least one except or a finally. Alone, it is a syntax error.
  • try with only finally is allowed: the clean-up happens, then the error still stops the program.
  • There may be many except clauses but only one finally, and it comes last.
  • Put the particular exception above a general one such as Exception, or it is never reached.
  • An except: with no name catches everything, spelling mistakes in your own code included. Name the exception instead.

A value is also being returned here. If that part is shaky, start with functions for Class 12.

Q3. Where do you use it?

Exception handling programs for Class 12

You need a handler wherever the program depends on something it does not control: what a person types, whether a file exists, how many records a file holds, or whether a key is present.

1. Ask again until it is righttyped values included
def read_marks(limit=70):
    """Return a whole number from 0 to limit."""
    while True:
        try:
            marks = int(input("Theory marks: "))
            if 0 <= marks <= limit:
                return marks
            print("Must be 0 to", limit)
        except ValueError:
            print("Digits only, please")

print("Saved:", read_marks())

Output

Theory marks: sixty
Digits only, please
Theory marks: 88
Must be 0 to 70
Theory marks: 61
Saved: 61

88 is not an exception. It converts well; a plain if rejects it.

2. Two things can go wrongtwo excepts
menu = {"idli": 30, "vada": 25, "dosa": 60}

def order_cost(item, plates):
    """Return the cost, or a message."""
    try:
        return menu[item] * int(plates)
    except KeyError:
        return "Not on the menu: " + item
    except ValueError:
        return "Plates must be a number"

print(order_cost("idli", "4"))
print(order_cost("puri", "2"))
print(order_cost("dosa", "two"))
print(order_cost("puri", "two"))

Output

120
Not on the menu: puri
Plates must be a number
Not on the menu: puri

The last call has both faults. menu[item] is worked out first, so KeyError is the one raised.

3. A text file that may be missingpoem.txt has 3 lines
def count_lines(filename):
    """Display the number of lines in a text file."""
    try:
        with open(filename) as f:
            lines = f.readlines()
        print(filename, "has", len(lines), "lines")
    except FileNotFoundError:
        print(filename, "was not found")
    finally:
        print("Search finished")

count_lines("poem.txt")
count_lines("peom.txt")

Output

poem.txt has 3 lines
Search finished
peom.txt was not found
Search finished
4. The end of a binary fileEOFError as a signal
import pickle

with open("nursery.dat", "wb") as f:
    for plant in (["Tulsi", 12], ["Neem", 4], ["Rose", 9]):
        pickle.dump(plant, f)

def total_plants():
    """Return the number of plants in all records."""
    total = 0
    f = open("nursery.dat", "rb")
    try:
        while True:
            total += pickle.load(f)[1]
    except EOFError:
        print("No more records")
    finally:
        f.close()
    return total

print("Plants:", total_plants())

Output

No more records
Plants: 25

The marking scheme for the 2026-27 sample paper gives a mark in Question 36 for exactly this: load() in a while loop with try and except.

5. Skip bad data, keep the resttry inside a loop
def average(readings):
    """Return the mean of the valid readings."""
    total = good = 0
    for r in readings:
        try:
            total += float(r)
            good += 1
        except ValueError:
            print("Skipped", r)
    try:
        return total / good
    except ZeroDivisionError:
        return "No valid reading"

print(average(["36.5", "NA", "38.5"]))
print(average(["NA", "-"]))

Output

Skipped NA
37.5
Skipped NA
Skipped -
No valid reading

With the try outside the loop, the first NA would have ended the whole loop.

6. The order of the exceptsa common trap
try:
    seats = int("5a")
except Exception:
    print("Something failed")
except ValueError:
    print("Not a whole number")
finally:
    print("Counter closed")

Output

Something failed
Counter closed

ValueError is a kind of Exception, so the general clause takes it first. Swap the two clauses to get the useful message.

Next, use these inside longer answers: file handling for Class 12, then CSV and binary files.

Q4. How much is enough?

What is in the exception handling syllabus for Class 12 in 2026-27?

The 083 syllabus line is brief: introduction, and handling exceptions using try-except-finally blocks. CBSE gives the chapter no marks of its own; it shares the 40 marks of Unit 1.

Read about, but not named in the line

IdeaIn one sentence
raiseMakes an exception happen on purpose.
assertChecks a condition and raises AssertionError if it is false.
else after exceptRuns only when try finished with no exception.
except ValueError as eKeeps the exception in a name so its message can be printed.

Textbooks often cover these, and your school may ask about them in a class test. Know the sentence for each. For the board, master the three named blocks first.

In the official 2026-27 sample paper, a 1-mark question asks what an except block leaves in a text file, and the 5-mark binary file answer relies on EOFError. So the chapter is examined through other chapters too. All the topics are listed on the Class 12 CS syllabus page.

Mistakes a marker sees first

What is writtenWhat goes wrongWrite instead
n = int(input()) above the tryThe ValueError happens outside, uncaughtPut the conversion inside try
except FileNotFound:NameError, when an exception arrives thereThe full name, FileNotFoundError
f.close() as the last line of trySkipped when an earlier line failswith, or close in finally
Closing f in finally when open() was in the tryIf open failed, f does not existOpen before the try, or use with
Twenty lines inside one tryNobody can tell which line was expected to failOnly the risky statements

Q5. Can you name it and trace it?

Exception handling Class 12 important questions with answers

Nineteen original questions: naming the exception, tracing the blocks, correcting code and writing short functions. Decide the exception first in each one, then follow the blocks.

One mark each

  1. Which block runs whether or not an exception occurs?
    Answer finally.
  2. Name the exception: int("7.5")
    Answer ValueError. int() converts strings of whole numbers only. float("7.5") would work.
  3. Name the exception: marks = (40, 35) followed by marks[0] = 45
    Answer TypeError. A tuple does not allow item assignment.
  4. Name the exception: "Pune".index("z")
    Answer ValueError, since the letter is not there. find() would give -1 without any exception.
  5. Can a try block be followed by a finally block alone?
    Answer Yes. The exception is not handled, but the finally statements run before the program stops.
  6. True or False: a missing bracket in a program can be handled by a try block in that same program.
    Answer False. It is a syntax error, found before the program starts running.
  7. If no exception occurs in try, which block is skipped?
    Answer The except block.
  8. Fill in the blank to complete the pair: try: with price = rates["bus"], then ______ KeyError:
    Answer except
  9. Assertion (A): A program with an except ValueError clause may still stop with an error. Reason (R): An except clause deals only with the kind of exception it names.
    Answer Both A and R are true, and R is the correct explanation of A.
  10. Assertion (A): finally cannot be written without except. Reason (R): finally is used for statements that must run in every case.
    Answer A is false but R is true.

Two marks, theory

  1. Differentiate between a syntax error and an exception, with one example of each.
    Answer A syntax error breaks the rules of the language and is found before the program runs, such as print("Hi". An exception arises while a correctly written program is running, such as 10 / 0, which raises ZeroDivisionError.
  2. What is the use of the finally block? Give one situation from your practical file.
    Answer It holds statements that must run in every case, usually clean-up. Example: closing a binary file after reading it, whether the reading ended normally or with an exception.

Two marks, correct the code

  1. Remove the four errors and underline each correction.
    Q13four errors
    Try:
        rate = 500 / int("5")
        print(rate)
    exept ZeroDivisionError
        print("Cannot divide")
    Finally:
        print("Over")
    Answer
    Q13 correctedhalf a mark each
    try:                            # 1. small t
        rate = 500 / int("5")
        print(rate)
    except ZeroDivisionError:       # 2. spelling  3. colon
        print("Cannot divide")
    finally:                        # 4. small f
        print("Over")

    Output

    100.0
    Over

Three marks, write the function

  1. Write letter_at(word, pos), where pos arrives as a string. Return the letter at that index. Return "Not a number" or "Out of range" when the position is unusable.
    Answer
    Q14one good answer
    def letter_at(word, pos):
        try:
            return word[int(pos)]
        except ValueError:
            return "Not a number"
        except IndexError:
            return "Out of range"
    
    print(letter_at("Kaveri", "2"))
    print(letter_at("Kaveri", "two"))
    print(letter_at("Kaveri", "6"))

    Output

    v
    Not a number
    Out of range
  2. Each line of a text file should hold a whole number. Write add_up(filename) to return the sum, ignoring lines that do not convert, and to return "No file" if the file is missing.
    Answer
    Q15donations.txt holds 250, five, 400
    def add_up(filename):
        total = 0
        try:
            with open(filename) as f:
                for line in f:
                    try:
                        total += int(line)
                    except ValueError:
                        pass
        except FileNotFoundError:
            return "No file"
        return total
    
    print(add_up("donations.txt"))
    print(add_up("donation.txt"))

    Output

    650
    No file

    int() ignores the newline at the end of each line, so no strip() is needed.

Two marks, output

  1. Predict the output.
    Q16predict
    def ask(values, i):
        try:
            print(values[i] + 1)
        except IndexError:
            print("too short")
        except TypeError:
            print("not a number")
        finally:
            print("*")
    
    ask([4, "7"], 0)
    ask([4, "7"], 1)
    ask([4, "7"], 2)
    Answer Output
    5
    *
    not a number
    *
    too short
    *
    Index 1 exists but holds a string, so adding 1 is a TypeError. Index 2 does not exist.
  2. Predict the output.
    Q17predict
    total = 0
    for x in ["4", "0", "b", "2"]:
        try:
            total += 8 // int(x)
        except ZeroDivisionError:
            total += 100
        except ValueError:
            total += 1000
    print(total)
    Answer Output
    1106
    2, then 100 for the zero, then 1000 for the letter, then 4. The loop carries on because the try is inside it.
  3. Predict the output.
    Q18predict
    def size(n):
        try:
            if n > 2:
                return "big"
            print("small")
        finally:
            print("end")
    
    print(size(5))
    size(1)
    Answer Output
    end
    big
    small
    end
    In the first call the value waits while finally prints, so "end" comes before "big".
  4. The file fan.txt does not exist before this code is run. What does it show?
    Q19predict
    def log(temp):
        f = open("fan.txt", "a")
        try:
            f.write(str(int(temp) + 1) + ";")
        except ValueError:
            f.write("?;")
        finally:
            f.close()
    
    for t in ["24", "hot", "30"]:
        log(t)
    f = open("fan.txt")
    print(f.read())
    f.close()
    Answer Output
    25;?;31;
    For "hot", int() fails before anything is written, so only the handler writes.

Enjoyed the tracing? There is a whole page of it: Class 12 CS output questions.

Your own red text

One to one classes begin with the error messages from your lab work. You read the last line first, name the exception, and find the statement.

Break it on purpose

You make a working file program fail in three ways, then add a handler for each and prove that it runs.

Letters in the margin

Trace questions are done as A, B, C, D, E, as in the tank program, until the path through the blocks is automatic.

One to one only

Short chapter, so learn it on your own programs

Exceptions are personal: yours come from the way you type, name files and convert values. That is why these classes are personalised one to one and nothing else, on your days, at your timing, with your code on the screen. A priority demo is the way to try it, a full class whose fee comes off the first month when you enrol. The free demo class is the lighter choice. Fees are monthly, nothing is charged for admission, and you are free to stop when a month ends.

Before you enrol · Try a class

Priority demo, at a slot you pick

a full live class of about 45 to 60 minutes

  • You run a file program of yours and the teacher breaks it
  • You name each exception before Python tells you
  • You add the handlers, and see which blocks run
  • A written skill report covering exceptions, files and tracing
Book a priority demo

The classes · Choose your own timing

Personalised one to one

₹4,999

per month, 4 private classes, fully flexible timing

  • Exceptions taught together with text, binary and CSV files
  • Debugging your practical file programs, which you write yourself
  • Trace and correction questions until the path is automatic
  • The rest of the 083 theory planned around your school tests
Ask for a personalised plan

If exceptions are your only worry, say so: the first classes can deal with just that and move on to files, where the marks are. If the trouble is deeper, in loops or in converting input, the teacher finds it early and goes back as far as needed. What you pay each month is shown on this page for your own country.

Studying outside India?

For 083 students whose school is abroad

Whether your CBSE school is in Sharjah, Jeddah, Bahrain or Jakarta, the line "try-except-finally" in your syllabus is the same. We fix class hours around your school day and weekend.

Where you liveTime differenceUsual class window, local timeFormat
India
every Indian city
Indian timeAny time you choosePersonalised 1-on-1
UAE and Oman
Dubai, Abu Dhabi, Sharjah, Muscat
1 h 30 min behind India3:00 PM to 9:00 PMPersonalised 1-on-1
Saudi Arabia, Qatar, Kuwait, Bahrain
Riyadh, Jeddah, Dammam, Doha, Kuwait City, Manama
2 h 30 min behind India3:00 PM to 9:00 PMPersonalised 1-on-1
Nepal
Kathmandu
15 min ahead of India4:30 PM to 9:00 PMPersonalised 1-on-1
Ethiopia and East Africa
Addis Ababa and East Africa Time
2 h 30 min behind India4:30 PM to 9:00 PMPersonalised 1-on-1
Singapore and Malaysia
Singapore, Kuala Lumpur
2 h 30 min ahead of India3:30 PM to 9:00 PMPersonalised 1-on-1

An error message reads the same in every country, which makes this an easy chapter to teach on a shared screen. Keep Python open, keep your practical programs in one folder, and tell us the hours that are free at home.

What families say

Rated 4.9 across 547 Google reviews

Real reviews from real families. We neither write nor commission them.

★★★★★

"The one step solution for my son. Modern Age Coders make learning coding so simple that kids love it. The teachers explain complex concepts clearly with practical exercises and interactive content."

Ria Mukherjee

Parent

★★★★★

"Modern Age Coders has been a game-changer for me. I struggled to grasp IT concepts and coding before joining, but their classes transformed everything. I can now confidently write complex programs with ease."

Samriddha Mondal

Student

★★★★★

"One of the most wonderful education centres out there. Education is not limited to school syllabus but focuses on skill development."

Vansh Agarwal

Student

★★★★★

"My child Dhairya is really enjoying the Modern Age Coders classes. This is his first online class and he eagerly looks forward to it. I can already see his improvement, and the teachers are very cooperative."

Sonam Oswal

Parent of Dhairya

★★★★★

"Modern Age Coders have wonderful teachers who teach in a clear, easy and practical way. The teacher boosts students' confidence and inspires them to learn without hesitation."

Sonu Goyal

Parent

★★★★★

"I highly recommend this computer coding class! The teachers are incredibly knowledgeable and passionate about coding."

Ritu Kedia

Parent

The rest of the Class 12 series

More pages for Class 12 students

Every page in the CBSE Class 12 Computer Science series, grouped by what you need.

Questions on exceptions

Exception handling in Class 12: questions students ask

What is exception handling in Python Class 12?

It is writing code that deals with errors which occur while a program is running, so the program can respond and not simply stop. In CBSE 083 for 2026-27 it is done with three blocks: try for the risky statements, except for the response to a named exception, and finally for statements that run in every case.

How many marks is exception handling in Class 12 Computer Science?

CBSE does not give the chapter separate marks. It is part of Unit 1, which carries 40 of the 70 theory marks. In the 2026-27 sample paper it is tested in a 1-mark question, and a try and except around pickle.load() earns credit inside the 5-mark binary file question.

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

A syntax error breaks a rule of Python, like leaving out a colon, and is reported before the program runs. An exception happens during the run, when a correctly written statement cannot be carried out, such as int("twelve"). Only exceptions can be handled by a try block in that program.

Does finally run if there is a return in try?

Yes. Python works out the value to be returned, runs the finally block, and only then goes back to the caller. So anything printed in finally appears before the caller prints the returned value. The check(8) example on this page prints checked 8 first and 12 second.

Can we use try without except in Python?

Yes, provided there is a finally block. The finally statements run and the exception then continues and stops the program, since nothing has handled it. Students use this form when a file must be closed whatever happens. A try with neither except nor finally is a syntax error.

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

The 083 line names introduction and handling exceptions using try-except-finally blocks. raise, assert and the else clause are not named in it. Many textbooks explain them, so know what each does in one sentence, and check with your teacher for school tests.

Which exceptions are important for Class 12 CS?

ZeroDivisionError, ValueError, TypeError, NameError, IndexError, KeyError, FileNotFoundError and EOFError cover most of what a Class 12 program meets. Learn one statement that raises each. ModuleNotFoundError is worth adding, because it is what a wrongly spelt import gives.

What is the difference between ValueError and TypeError?

TypeError means the kind of object is wrong for the operation, such as adding a string to an integer. ValueError means the kind is right but the particular value is not, such as int("abc"), where a string is accepted but this one cannot be converted.

Why is EOFError used in binary file programs?

pickle.load() reads one record at a time and does not say how many are left. When none remain it raises EOFError. Catching that exception is the usual way to end the reading loop, so here it is a normal event and not a fault.

Is there one to one tuition for Class 12 Python exceptions and files?

Yes. Modern Age Coders holds live one to one classes for 083 at your own days and timing. Start with a priority demo, about 45 to 60 minutes with a written skill report, and its fee is adjusted against your first month if you enrol. You may take a free demo class instead.

Start

Paste your last error message.

In a free demo class the teacher reads that message with you: the name, the line, the cause, the fix. Ten minutes of this teaches more than a list of definitions.

The priority demo goes further. You choose the slot, bring one of your file programs, and spend a whole class making it safe against bad input, missing files and the end of the data. A written skill report follows, and the fee is taken off your first month if you enrol.

More programs to test yourself on: Python programs for CBSE Class 12, and the Class 12 CS crash course if time is short.

WhatsApp us · +91 91233 66161 · connect@modernagecoders.com

Every class is live video. The form requests a callback and reserves nothing.

We call within a few hours. No card, no enrolment fee.

Want it sooner? Book a priority demo

A full live class of about 45 to 60 minutes at a slot you pick, with a written skill report and learning roadmap on WhatsApp afterwards. The fee is adjusted against your first month if you enrol.

Book a priority demo

Keep exploring Modern Age Coders

By class and age

Learn more

Free resources

From the blog

Start here