Worksheets › Class 12 › Exception Handling in Python
Class 12 · Computer Science worksheetException Handling in Python
CBSE Computer Science. Syntax errors and exceptions, built-in exceptions, raise and assert, try, except, else and finally traced line by line. Every sheet has 20 questions in three sections and an answer key, and the questions change every time.
Sample questions
Real questions from this chapter, as the app sets them. Tap Answer to see the answer and working.
Section A · multiple choice
- 1.
An error in the rules of writing Python (such as a missing colon) is a:
- logical error
- ValueError
- exception at run time
- syntax error
Answer
(d) syntax error
- 2.
Which exception does this code raise? x = float('pi')
- ValueError
- NameError
- IOError
- TypeError
Answer
(a) ValueError
the string cannot be read as a number
- 3.
What does this print? (Output lines are separated by commas.) L = [40, 10, 88] try: n = int('five') print(30 // n) print(L[n]) except ZeroDivisionError: print('Cannot divide') except ValueError: print('Not a number') except IndexError: print('Bad index') else: print('All fine') finally: print('Done')
- Not a number, Done
- Not a number
- 30, Bad index, Done
- 30, 0, All fine, Done
Answer
(a) Not a number, Done
int() of a word raises ValueError
Section B · short answer
- 4.
What is the difference between a syntax error and an exception?
Answer
A syntax error breaks the rules of the language and stops the program from running at all; an exception happens while a correct program runs, e.g. dividing by zero.
- 5.
Name the exception raised by this code. L = [1, 2, 5] print(L[6])
Answer
IndexError
L has indices 0 to 2 only
Section C · long answer
- 6.
Explain the try … except … else … finally statement with a program that divides two numbers typed by the user.
Answer
try: a = int(input()); b = int(input()); c = a / b; except ZeroDivisionError: print('b cannot be 0'); except ValueError: print('Enter whole numbers'); else: print(c); finally: print('Done'). Only one except runs; else runs when nothing went wrong; finally always runs.
Fresh sheets for your child
In the app, every Exception Handling in Python sheet is new: the app remembers the questions your child has already had and leaves them out. Print the sheet as a PDF, or use notebook mode and write the answers in a notebook.
Coming soon for Android and iPhone.