Home › Free notes › Class 12 Computer Science › Exception Handling in Python
Exception Handling in Python – Class 12 Computer Science notes, important questions and MCQs
NCERT Class 12 Computer Science, chapter 1. Notes, key terms, important questions with answers and MCQs.
Chapter overview
Errors in Python are of two broad kinds: syntax errors, detected before the program runs, and exceptions, which occur during execution. Python has many built-in exceptions, and programmers can raise exceptions using raise and assert. Exception handling with try, except, else and finally lets a program deal with errors gracefully instead of crashing.
Errors and exceptions
- Syntax errors (parsing errors) occur when the code breaks Python's grammar; the program does not start until they are fixed.
- Exceptions are runtime errors; built-in exceptions include ZeroDivisionError, ValueError, TypeError, NameError, IndexError, KeyError, ImportError, IOError, EOFError, OverflowError and IndentationError (a kind of syntax error).
- raise throws an exception explicitly, for example raise ValueError('Negative value'); assert tests a condition and raises AssertionError if it is False, for example assert age >= 0.
Handling exceptions
- Code that may cause an exception is placed in a try block; matching except blocks handle specific exceptions, and a bare except catches any exception; multiple except clauses can follow one try.
- The else block runs only if no exception occurs in try; the finally block always runs, whether or not an exception occurs, and is used for clean-up such as closing files.
- When an exception occurs, Python creates an exception object and searches for a handler (catching the exception); if none is found, the program terminates with a traceback.
Key terms
- Exception
- an error that occurs during program execution
- try block
- the block containing code that may raise an exception
- except block
- the block that handles a raised exception
- finally block
- a block that always executes, used for clean-up
- raise
- a statement used to throw an exception explicitly
Important questions with answers
Distinguish between syntax errors and exceptions.2 marks
Syntax errors occur when code does not follow Python's grammar, such as a missing colon, and are detected before execution, so the program does not run. Exceptions occur during execution even when the syntax is correct, such as division by zero, and can be handled using try and except.
Explain the use of the finally clause with an example.3 marks
The finally block always executes after try and except, whether an exception occurred or not, so it is used for clean-up actions such as closing files or releasing resources. For example: try: f = open('data.txt'); print(f.read()), except IOError: print('Error'), finally: print('Done'). 'Done' is printed in every case.
Explain exception handling in Python with a program that divides two numbers entered by the user.5 marks
Exception handling allows a program to respond to runtime errors without crashing. The statements that may cause an error are written in a try block. If an exception occurs, Python stops executing the try block, creates an exception object and looks for a matching except block. Program: try: a = int(input('Enter numerator: ')); b = int(input('Enter denominator: ')); result = a / b, except ValueError: print('Please enter integers only'), except ZeroDivisionError: print('Denominator cannot be zero'), else: print('Result =', result), finally: print('Execution complete'). Explanation: if the user enters text such as 'ten', int() raises ValueError and the first handler prints a message. If the denominator is 0, a / b raises ZeroDivisionError and the second handler runs. If no exception occurs, the else block prints the result; for inputs 10 and 4 it prints Result = 2.5. The finally block runs in all cases, printing 'Execution complete'. Multiple except blocks allow different responses to different errors, and the order of handlers matters, with more specific exceptions placed before general ones. The raise statement can also be used to create custom errors, such as raising ValueError for a negative age.
Quick revision
- Syntax errors versus exceptions.
- Built-in exceptions.
- raise and assert.
- try, except, else, finally.
Exam tips
- Order: try → except → else → finally.
- Put specific except clauses before a general one.
Practice MCQs
An error that occurs while the program is running is called
- syntax error
- exception
- comment
- keyword
Show answer
Answer: (b) exception. Also called a runtime error.
Dividing a number by zero raises
- ValueError
- ZeroDivisionError
- TypeError
- NameError
Show answer
Answer: (b) ZeroDivisionError. Example: 5 / 0.
The block that always executes, whether or not an exception occurs, is
- finally
- try
- else
- except
Show answer
Answer: (a) finally. It is used for clean-up.
int('abc') raises
- TypeError
- IndexError
- KeyError
- ValueError
Show answer
Answer: (d) ValueError. The value is of the right type but inappropriate.
Accessing L[10] when the list has 5 elements raises
- KeyError
- NameError
- IndexError
- EOFError
Show answer
Answer: (c) IndexError. The index is out of range.
The else block in exception handling runs when
- an exception occurs
- always
- no exception occurs in the try block
- never
Show answer
Answer: (c) no exception occurs in the try block. It follows the except blocks.
What does assert x > 0 do when x is -5
- raises AssertionError
- prints -5
- returns False silently
- converts x to 5
Show answer
Answer: (a) raises AssertionError. The condition is False.
Using an undefined variable total in an expression raises
- ValueError
- NameError
- TypeError
- SyntaxError
Show answer
Answer: (b) NameError. The name is not defined.
All chapters of Class 12 Computer Science
Written by Kundali IQ from standard, well-established facts to help with revision. This is not an official NCERT publication; always read your textbook too.