★★★★★
"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
CBSE Class 12 · Computer Science 083 · Exception handling 2026-27
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
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.

Board / 083 track
Exception handling sits between functions and files here, so your file programs can use handlers from the first one.
Open the course →
Python / Projects
Build small programs that survive wrong input. A useful route if error messages still feel like a telling-off instead of a clue.
Open the course →
SQL / Apps
The closing month joins Python to a database, which is a natural place to use what you learn in this chapter.
Open the course →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?
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 mistake | When it shows | Example | Can try-except help? |
|---|---|---|---|
| Syntax error | Before any line runs | A missing colon after if | No. The program never starts, so its try never runs |
| Exception (run-time error) | While running, at one statement | int("twelve") | Yes, if that statement is inside a try |
| Logical error | Never reported. The answer is wrong | total = marks * 3 where + was meant | No. Python sees nothing wrong |
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.
| Exception | A statement that raises it | Message |
|---|---|---|
| ZeroDivisionError | 60 / 0 | division by zero |
| ValueError | int("twelve") | invalid literal for int() with base 10: 'twelve' |
| TypeError | "Rs " + 50 | can only concatenate str (not "int") to str |
| NameError | print(totl) | name 'totl' is not defined |
| IndexError | [4, 7][2] | list index out of range |
| KeyError | {"tea": 10}["milk"] | 'milk' |
| FileNotFoundError | open("gone.txt") | [Errno 2] No such file or directory: 'gone.txt' |
| EOFError | pickle.load(f) with no record left | Ran out of input |
| ModuleNotFoundError | import maths | No 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?
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.
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.
Statements run in order, as usual.
The remaining try statements are dropped. That is why B is missing in the second call.
The except clauses are checked from the top, and at most one of them runs.
With a failure or without, matched or not.
If the exception was handled, or never happened, the lines below continue. If not, the program ends with the error.
| Situation | try | except | finally | Statements below |
|---|---|---|---|---|
| No exception | Runs fully | Skipped | Runs | Run |
| Exception with a matching except | Runs up to the failure | Runs | Runs | Run |
| Exception with no matching except | Runs up to the failure | Skipped | Runs | Not run, program stops |
| The except block itself fails | Runs up to the failure | Runs up to its own failure | Runs | Not run, program stops |
return inside try | Runs up to the return | Skipped | Runs, then the value goes back | Not run, function has ended |
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
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.except clauses but only one finally, and it comes last.Exception, or it is never reached.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?
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.
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.
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.
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
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.
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.
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?
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.
| Idea | In one sentence |
|---|---|
raise | Makes an exception happen on purpose. |
assert | Checks a condition and raises AssertionError if it is false. |
else after except | Runs only when try finished with no exception. |
except ValueError as e | Keeps 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.
| What is written | What goes wrong | Write instead |
|---|---|---|
n = int(input()) above the try | The ValueError happens outside, uncaught | Put the conversion inside try |
except FileNotFound: | NameError, when an exception arrives there | The full name, FileNotFoundError |
f.close() as the last line of try | Skipped when an earlier line fails | with, or close in finally |
Closing f in finally when open() was in the try | If open failed, f does not exist | Open before the try, or use with |
| Twenty lines inside one try | Nobody can tell which line was expected to fail | Only the risky statements |
Q5. Can you name it and trace it?
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.
finally.int("7.5") int() converts strings of whole numbers only. float("7.5") would work.marks = (40, 35) followed by marks[0] = 45 "Pune".index("z") find() would give -1 without any exception.except block.try: with price = rates["bus"], then ______ KeyError: exceptexcept ValueError clause may still stop with an error. Reason (R): An except clause deals only with the kind of exception it names. print("Hi". An exception arises while a correctly written program is running, such as 10 / 0, which raises ZeroDivisionError.Try:
rate = 500 / int("5")
print(rate)
exept ZeroDivisionError
print("Cannot divide")
Finally:
print("Over")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
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. 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
add_up(filename) to return the sum, ignoring lines that do not convert, and to return "No file" if the file is missing. 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.
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)5*not a number*too short*total = 0
for x in ["4", "0", "b", "2"]:
try:
total += 8 // int(x)
except ZeroDivisionError:
total += 100
except ValueError:
total += 1000
print(total)1106def size(n):
try:
if n > 2:
return "big"
print("small")
finally:
print("end")
print(size(5))
size(1)endbigsmallenddef 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()25;?;31;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.
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.
You make a working file program fail in three ways, then add a handler for each and prove that it runs.
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
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
a full live class of about 45 to 60 minutes
The classes · Choose your own timing
₹4,999
per month, 4 private classes, fully flexible timingtwo private classes a week, at a time set with you
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?
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 live | Time difference | Usual class window, local time | Format |
|---|---|---|---|
| India every Indian city | Indian time | Any time you choose | Personalised 1-on-1 |
| UAE and Oman Dubai, Abu Dhabi, Sharjah, Muscat | 1 h 30 min behind India | 3:00 PM to 9:00 PM | Personalised 1-on-1 |
| Saudi Arabia, Qatar, Kuwait, Bahrain Riyadh, Jeddah, Dammam, Doha, Kuwait City, Manama | 2 h 30 min behind India | 3:00 PM to 9:00 PM | Personalised 1-on-1 |
| Nepal Kathmandu | 15 min ahead of India | 4:30 PM to 9:00 PM | Personalised 1-on-1 |
| Ethiopia and East Africa Addis Ababa and East Africa Time | 2 h 30 min behind India | 4:30 PM to 9:00 PM | Personalised 1-on-1 |
| Singapore and Malaysia Singapore, Kuala Lumpur | 2 h 30 min ahead of India | 3:30 PM to 9:00 PM | Personalised 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
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
Every page in the CBSE Class 12 Computer Science series, grouped by what you need.
CBSE Class 12 Informatics Practices (065): Class 12 IP practical file Class 12 IP project with source code Class 12 IP sample paper practice Class 12 IP important questions
CBSE Class 12 Information Technology (802): IT 802 practical and project file IT 802 Java notes and programs IT 802 notes
CBSE Class 11 CS, IP and AI: Class 11 CS practical file Class 11 IP practical file CS or IP in Class 11
ISC Computer Science (868): ISC Class 12 CS syllabus 2027 ISC Class 12 CS practice paper ISC Class 12 practical questions solved ISC Boolean algebra and K-maps
Program lists with output: Class 12 CS practical file 20 Python programs for Class 12 Menu-driven programs in Python
Questions on exceptions
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.
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.
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.
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.
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.
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.
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.
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.
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.
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
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.
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