Built-in Exceptions in Python: What Raises Each One (Class 12 Computer Science)
Updated 16 October 2026 · Fact-checked
Built-in exceptions are the error types Python already defines and raises by itself, such as ZeroDivisionError (dividing by zero), ValueError (right type, unsuitable value), TypeError (wrong type for an operation), IndexError (index out of range), NameError (undefined name) and IOError (a file that cannot be opened). Each can be caught by naming it in an except clause.
Match each faulty line to the exception Python raises, so you can write the correct except clause for it.
Illustration drawn for QuestionBuddy.
Understand Built-in Exceptions
Python comes with a set of built-in exceptions, ready-made classes for the commonly occurring errors. When one of these situations happens, the interpreter raises the matching exception and prints its name and a message. Knowing the names lets you predict what a faulty line will raise and write the right except clause. NCERT Table 1.1 lists twelve:
- SyntaxError: the code breaks the rules of Python, such as a missing colon or bracket.
- IndentationError: wrong indentation; it is a kind of SyntaxError, so it too is reported before the program runs.
- ValueError: an argument has the right type but an unsuitable value, for example
int('4.0'),int('abc')ormath.sqrt(-4). - TypeError: an operation gets a value of the wrong type, for example
'abc' + 5or'10' / 2. - ZeroDivisionError: the second operand of
/,//or%is zero. - IndexError: an index is out of range for a list, tuple or string.
- NameError: a variable or function name is not defined.
- IOError: a file cannot be opened. In Python 3, IOError is another name for OSError; opening a missing file for reading raises FileNotFoundError, which is a kind of IOError, so
except IOErrorcatches it. - EOFError:
input()reaches the end of the input without reading any data. - ImportError: a module cannot be imported; a misspelt module name gives ModuleNotFoundError, a kind of ImportError.
- KeyboardInterrupt: the user interrupts a running program from the keyboard.
- OverflowError: the result of a calculation is too large for its numeric type. Floats can overflow (
2.0 ** 5000,math.exp(1000)), but Python integers grow as needed, so2 ** 5000works.
Two more appear often in board questions though they are not in the NCERT table: KeyError (a missing dictionary key) and UnboundLocalError (a local variable read before assignment, a kind of NameError).
Value or type? This is the commonest confusion. Ask: is the operation possible for this type at all? int() accepts strings, so int('abc') has the right type but a bad value: ValueError. A string cannot be divided by a number at all, so '10' / 2 is a TypeError.
Because some exceptions are kinds of others, an except clause for the general one also catches the particular ones: except IOError catches FileNotFoundError, and except ImportError catches ModuleNotFoundError.
Recent sample papers ask 1-mark items such as 'which exception does this line raise?' and use these names inside output and assertion-reason questions.
Built-in Exceptions: key facts
- NCERT Table 1.1 in brief
SyntaxError code breaks Python's rules ValueError right type, unsuitable value IOError file cannot be opened KeyboardInterrupt user interrupts the program ImportError module not found EOFError input() reaches end of input ZeroDivisionError divisor is zero IndexError index out of range NameError name not defined IndentationError wrong indentation TypeError wrong type for the operation OverflowError result too large for the type - NCERT Class XII Computer Science 1.4.
- Statement → exception
int('4.0') ValueError 'abc' + 5 TypeError 7 % 0 ZeroDivisionError [1, 2][2] IndexError print(total) with no total NameError open('nofile.txt') FileNotFoundError (an IOError) {'a' 1}['z']: KeyError 2.0 ** 5000 OverflowError - Each one checked by running it.
- Families
- FileNotFoundError is an IOError (OSError)
- ModuleNotFoundError is an ImportError
- IndentationError is a SyntaxError
- UnboundLocalError is a NameError
- except on the family name also catches its members.
- ValueError or TypeError?
- 1.Operation allowed for this type, bad value
- 2.ValueError | Operation not allowed for this type
- 3.TypeError
- int('abc') is ValueError; int(None) is TypeError.
How to answer Built-in Exceptions questions
To name the exception a statement raises, go through this checklist in order.
- 1Is the code itself badly written (missing colon, bracket, wrong indentation)? Then it is SyntaxError or IndentationError, reported before anything runs.
- 2Is a name used that was never assigned? NameError (UnboundLocalError if it is a local read before assignment).
- 3Is an operator or function applied to a type that cannot take it, such as str + int? TypeError.
- 4Is the type fine but the value unsuitable, such as int('12a') or sqrt of a negative number? ValueError.
- 5Is a divisor zero in /, // or %? ZeroDivisionError.
- 6Is an index past the end of a sequence (IndexError) or a key missing from a dictionary (KeyError)?
- 7Does it involve a file, input() or import? IOError/FileNotFoundError, EOFError or ImportError.
Built-in Exceptions 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.
Different exceptions, different messages
Suppose a fitness app asks for the minutes walked and divides 600 calories by them to show calories per minute; a user may type text, a zero, or a valid number.
Write the handler so each mistake gets its own message, and show the output for the inputs '0', 'twenty' and '25'.
Try it first, then show the solutionSolution
- int('twenty') raises ValueError; 600 / 0 raises ZeroDivisionError; '25' works.
for entry in ['0', 'twenty', '25']: try: mins = int(entry) print('Calories per minute:', 600 / mins) except ValueError: print('Please type a number') except ZeroDivisionError: print('Minutes cannot be zero')
Answer: Minutes cannot be zero
Please type a number
Calories per minute: 24.0
Memory hook: Name the problem and you can give the right advice.
IOError for a missing file
Imagine a report-card program that opens marks.txt, but the file has not been copied to the computer yet.
Which exception is raised, and how should the program respond?
Try it first, then show the solutionSolution
- Opening a missing file for reading raises FileNotFoundError, which is a kind of IOError.
try: f = open('marks.txt') print(f.read()) f.close() except IOError: print('marks.txt not found - copy the file and retry')
Answer: marks.txt not found - copy the file and retry
Memory hook: IO = In/Out: when the file door is locked, it is an IOError.
Tricks to remember Built-in Exceptions
Short memory aids. Say each one aloud once, then use it on a question the same day.
Type is the kind, value is the content
TypeError: 'you can't do this with that kind of thing'. ValueError: 'right kind of thing, wrong content'.
Use it when: Choosing between ValueError and TypeError.
Index for positions, Key for labels
Sequences complain with IndexError; dictionaries complain with KeyError.
Use it when: Lookup errors.
Syntax family strikes first
SyntaxError and IndentationError are caught at the gate, before the program runs; the rest strike during the run.
Use it when: Questions on when an error is detected.
Floats overflow, ints just grow
2 5000 is fine; 2.0 5000 raises OverflowError.
Use it when: OverflowError items.
Built-in Exceptions: solved examples
Ordered from board level to HOTS. Try each one before you open the solution.
Example 1: Name the exception · 1 mark · MCQBoard level
Which exception does 'abc' + 5 raise?
(a) ValueError (b) TypeError (c) NameError (d) SyntaxError
Try it first, then show the solutionSolution
- + between a string and an integer is not defined for these types.
- That is a wrong type for the operation.
Answer: (b) TypeError
Example 2: Four statements, four exceptions · 2 marks · Short answerHarder board level
Name the exception raised by each statement when run on its own:
(i) [1, 2][2] (ii) int('4.0') (iii) print(total), where total was never assigned (iv) 7 % 0
Try it first, then show the solutionSolution
- (i) A two-item list has indexes 0 and 1: IndexError. (½ mark)
- (ii) int() of a string accepts only whole-number text: ValueError. (½ mark)
- (iii) Undefined name: NameError. (½ mark)
- (iv) % by zero: ZeroDivisionError. (½ mark)
Answer: IndexError, ValueError, NameError, ZeroDivisionError
Example 3: One handler for each problem · 3 marks · Short answerHarder board level
pairs = [(10, 2), (5, 0), (8, 'x'), (9,)]. Write a loop that prints a // b for each pair, and handles ZeroDivisionError, TypeError and IndexError with a suitable message each. Give the output.
Try it first, then show the solutionSolution
- Loop and compute inside try (1 mark); three except clauses (1½ marks); correct output (½ mark).
pairs = [(10, 2), (5, 0), (8, 'x'), (9,)] for p in pairs: try: print(p[0] // p[1]) except ZeroDivisionError: print('cannot divide by zero') except TypeError: print('not a number') except IndexError: print('missing value')- (9,) has only index 0, so p[1] raises IndexError.
Answer: 5
cannot divide by zero
not a number
missing value
Example 4: IOError catches a missing file · 2 marks · Short answerHarder board level
Predict the output when data.txt does not exist:
try:
f = open('data.txt', 'r')
print('opened')
except IOError:
print('IOError caught')
except FileNotFoundError:
print('FileNotFoundError caught')Try it first, then show the solutionSolution
- Opening a missing file for reading raises FileNotFoundError. (1 mark)
- FileNotFoundError is a kind of IOError, and the first matching clause wins, so except IOError catches it; the second clause never runs. (1 mark)
Answer: IOError caught
Example 5: EOFError from input() · 1 mark · Very short answerHOTS / competency
A program is run with its input redirected from an empty file. Predict the output:
try:
name = input()
print('Hello', name)
except EOFError:
print('No input given')
except ValueError:
print('Bad value')Try it first, then show the solutionSolution
- input() reaches the end of the input without reading anything, so it raises EOFError.
- The EOFError clause prints its message.
Answer: No input given
Example 6: Case study: a calculator app · 4 marks · Case-basedHOTS / competency
Suppose a school calculator app runs these user actions:
(i) sqrt of -9 using math.sqrt (ii) the float power 10.0 ** 400 (iii) memory['M2'] when only 'M1' is stored (iv) importing a module typed as 'mathh'.
Name the exception for each and say which except clause would catch (iv). (4 marks)
Try it first, then show the solutionSolution
- (i) math.sqrt(-9): right type, impossible value → ValueError (math domain error).
- (ii) 10.0 ** 400 is larger than the biggest float → OverflowError.
- (iii) Missing dictionary key → KeyError.
- (iv) import mathh → ModuleNotFoundError, which is a kind of ImportError, so except ImportError catches it.
Answer: (i) ValueError (ii) OverflowError (iii) KeyError (iv) ModuleNotFoundError, caught by except ImportError
Where students lose marks in Built-in Exceptions
The slips examiners see most often, and what to write instead.
Mistake: Calling int('abc') a TypeError
int() does accept strings; the problem is the value inside the string.
Wrong working
int('abc') → TypeError
Right working
int('abc') → ValueError
Do this: Ask whether the operation is allowed for the type at all; if yes, it is a ValueError.
Usually costs: 1 mark.
Mistake: Using IndexError for a missing dictionary key
Dictionaries raise KeyError.
Wrong working
except IndexError: # for d['z']
Right working
except KeyError: # for d['z']
Do this: Index for sequences, Key for dictionaries.
Usually costs: 1 mark.
Mistake: Misspelling exception names
An unknown name in an except clause itself raises NameError when Python checks it.
Wrong working
except ZeroDivideError:
Right working
except ZeroDivisionError:
Do this: Learn the exact spellings with their capital letters.
Usually costs: Half to 1 mark.
Mistake: Thinking SyntaxError can be caught in the same program
A syntax error stops the program from starting, so its own try block never runs.
Do this: Say that syntax errors must be corrected in the code; exceptions are what try/except handles.
Usually costs: 1 mark in reasoning questions.
Exam tips
- Make a two-column revision card of NCERT Table 1.1 (name → cause) and learn one example statement for each.
- In 'name the exception' items, run the line in your head step by step: the first failing operation decides the exception.
- Write 'IOError' or 'FileNotFoundError' for a missing file: NCERT uses IOError, and both are accepted Python names.
- When asked to handle invalid input, catch ValueError around int(input()).
- Keep KeyError and UnboundLocalError in mind; they are not in the NCERT table but appear in output questions.
Practice questions on Built-in Exceptions
Write each answer on paper first. Open the hint only if you are stuck, and the answer only when you have finished.
Q1 · 1 mark · MCQBoard level
Which exception is raised when the index of a list is out of range?
(a) KeyError (b) ValueError (c) IndexError (d) RangeErrorHint
Positions in a sequence.
Answer
(c) IndexError
Q2 · 1 mark · Very short answerBoard level
Which exception does '10' / 2 raise?
Hint
Can a string be divided at all?
Answer
TypeError
Q3 · 1 mark · MCQBoard level
Which statement raises ZeroDivisionError?
(a) 0 / 5 (b) 5 // 0 (c) 0 * 5 (d) 5 - 0Hint
Zero must be the divisor.
Answer
(b) 5 // 0
Q4 · 2 marks · Short answerHarder board level
Predict the output:
for x in [10, 'a', 0, None]: try: print(100 / x) except ZeroDivisionError: print('Z') except TypeError: print('T')Hint
None cannot be a divisor either, but not because it is zero.
Answer
10.0
T
Z
TQ5 · 2 marks · Short answerHarder board level
Write code that reads a number from the list vals = ['16', '-4', 'nine'], prints its square root using math.sqrt, and prints 'invalid' for any value that raises ValueError. Give the output.
Hint
Both int('nine') and math.sqrt(-4) raise ValueError.
Answer
import math vals = ['16', '-4', 'nine'] for v in vals: try: print(math.sqrt(int(v))) except ValueError: print('invalid')Output: 4.0, invalid, invalid (one per line)
Q6 · 1 mark · Assertion-reasonHarder board level
Assertion (A): An IndentationError is reported before any statement of the program is executed.
Reason (R): IndentationError is a kind of SyntaxError.
(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
When are syntax errors found?
Answer
(a) Both are true and R explains A: syntax errors, including indentation errors, are found when the code is parsed, before it runs.
Q7 · 2 marks · Short answerHOTS / competency
Predict the output:
try: a = 2 ** 5000 print('int ok', len(str(a))) b = 2.0 ** 5000 print('float ok') except OverflowError: print('overflow')Hint
Which of the two types has a size limit?
Answer
int ok 1506
overflow
(the integer has 1506 digits and is fine; the float power exceeds the float limit).
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.Which exception does int('4.0') raise?Show answer
ValueError.
2.Which exception is raised when input() finds no data?Show answer
EOFError.
3.Which exception is raised for an undefined variable?Show answer
NameError.
4.What does 2.0 ** 5000 raise?Show answer
OverflowError.
5.Does except IOError catch FileNotFoundError?Show answer
Yes; FileNotFoundError is a kind of IOError (OSError).
6.Which exception does importing a misspelt module raise?Show answer
ModuleNotFoundError, a kind of ImportError.
Built-in Exceptions: frequently asked questions
What are built-in exceptions in Python?
They are exception classes that Python defines in advance for common errors, such as ZeroDivisionError, ValueError, TypeError, IndexError and NameError. The interpreter raises them automatically when the error happens.
What is the difference between ValueError and TypeError?
TypeError means the operation cannot be done with that type at all, such as adding a string to an integer. ValueError means the type is acceptable but the value is not, such as int('abc').
Which built-in exceptions does NCERT list for Class 12?
Table 1.1 lists SyntaxError, ValueError, IOError, KeyboardInterrupt, ImportError, EOFError, ZeroDivisionError, IndexError, NameError, IndentationError, TypeError and OverflowError.
Can I catch more than one built-in exception with one try?
Yes. Write one except clause for each exception you expect, most specific first, and optionally a bare except at the end for anything else.