2nd pu notes

2nd PUC Computer Science quick Notes |Exception Handling in Python

Venkatesh A August 20, 2026 20 min read
2nd PUC / Class 12 • Computer Science

Complete Short Notes & Exam Preparation Guide

Based only on the NCERT textbook

verakworld.com

Chapter Overview

While executing a Python program, the program may not execute, may produce unexpected output, or may behave abnormally. Such situations can occur due to syntax errors, runtime errors, or logical errors.

In Python, exceptions are errors that are triggered automatically. Exceptions can also be forcefully triggered and handled through program code. This chapter explains exception handling in Python programs.

verakworld.com

1.1 Introduction

Meaning

Sometimes while executing a Python program, the program does not execute at all or executes but produces unexpected output or behaves abnormally. These situations occur because of syntax errors, runtime errors, or logical errors.

Key Definition: Exceptions are errors that get triggered automatically in Python. They can also be forcefully triggered and handled through program code.
⭐ Exam Point: Exception handling is used to deal with exceptional situations that may occur during execution of a Python program.
verakworld.com

1.2 Syntax Errors

Definition: Syntax errors occur when the rules of the particular programming language have not been followed while writing a program. They are also known as parsing errors.

Important Points

  • Syntax errors are detected by the interpreter.
  • When a syntax error occurs, the interpreter does not execute the program.
  • The error must be rectified and the program must be saved and rerun.
  • Python displays the name of the error and a short description.
  • In script mode, an error dialog box can display the error information.
⭐ Exam Point: Program execution starts only after the syntax error is corrected.
verakworld.com

1.3 Exceptions

Even when a statement or expression is syntactically correct, an error may occur during its execution. Examples given in the textbook include trying to open a file that does not exist and division by zero.

Definition: An exception is a Python object that represents an error.

Raising an Exception

When an error occurs during execution of a program, an exception is said to have been raised. The programmer needs to handle the exception so that the program does not terminate abnormally.

Important Points

  • Exceptions can disrupt the normal execution of a program.
  • A programmer can anticipate erroneous situations.
  • Appropriate code can be included to handle those situations.
  • SyntaxError is also an exception.
  • Other exceptions are generally generated when the program is syntactically correct.
⭐ Exam Point: Every syntax error is an exception, but exceptions are not limited to syntax errors.
verakworld.com

1.4 Built-in Exceptions

Commonly occurring exceptions are usually defined in the compiler/interpreter. These are called built-in exceptions.

Python’s standard library contains built-in exceptions for commonly occurring errors. When a built-in exception occurs, the appropriate exception handler code can display the reason along with the raised exception name.

S. No. Name of the Built-in Exception Explanation
1 SyntaxError Raised when there is an error in the syntax of Python code.
2 ValueError Raised when a built-in method or operation receives an argument having the right data type but mismatched or inappropriate values.
3 IOError Raised when the file specified in a program statement cannot be opened.
4 KeyboardInterrupt Raised when the user accidentally hits the Delete or Esc key while executing a program and the normal flow is interrupted.
5 ImportError Raised when the requested module definition is not found.
6 EOFError Raised when the end-of-file condition is reached without reading any data by input().
7 ZeroDivisionError Raised when the denominator in a division operation is zero.
8 IndexError Raised when the index or subscript in a sequence is out of range.
9 NameError Raised when a local or global variable name is not defined.
10 IndentationError Raised due to incorrect indentation in the program code.
11 TypeError Raised when an operator is supplied with a value of incorrect data type.
12 OverFlowError Raised when the result of a calculation exceeds the maximum limit for numeric data type.
Remember: A programmer can also create custom exceptions according to requirements. These are called user-defined exceptions.
verakworld.com

1.5 Raising Exceptions

When an error is detected, the Python interpreter raises or throws an exception. Exception handlers are designed to execute when a specific exception is raised.

Programmers can also forcefully raise exceptions by using the raise and assert statements.

  • Raising an exception interrupts the normal flow of program execution.
  • Control moves to the exception handler code.
  • No further statement in the current block is executed after the exception is raised.
verakworld.com

1.5.1 The raise Statement

The raise statement is used to throw an exception.

Syntax
raise exception-name[(optional argument)]

The optional argument is generally a string displayed when the exception is raised.

The error raised may be a built-in exception or a user-defined exception.

Important Behaviour

  • After an exception is raised, the normal execution flow is interrupted.
  • The statement following the raise statement is not executed.
  • Python can display a stack traceback.

Stack Traceback

A stack traceback is a structured block of text containing information about the sequence of function calls made in the branch of execution where the exception was raised.

⭐ Exam Point: The raise statement is used to forcefully throw an exception.
verakworld.com

1.5.2 The assert Statement

Definition: An assert statement is used to test an expression in the program code. If the result of testing is false, an exception is raised.

It is generally used at the beginning of a function or after a function call to check for valid input.

Syntax
assert Expression[,arguments]

How assert Works

  1. Python evaluates the expression after the assert keyword.
  2. If the expression is true, execution continues.
  3. If the expression is false, an AssertionError is raised.
  4. The exception can be handled like other exceptions.
Program 1-1 — Use of assert Statement
print("use of assert statement")
def negativecheck(number):
    assert(number>=0), "OOPS... Negative Number"
    print(number*number)

print (negativecheck(100))
print (negativecheck(-350))
Program Point: When a negative value such as -350 is passed, an AssertionError is raised and subsequent statements are not executed. The message given in the textbook is OOPS…. Negative Number.
verakworld.com

1.6 Handling Exceptions

Definition: Exception handling is the process of writing additional code in a program to provide proper messages or instructions to the user when an exception occurs.

Exception handling helps prevent a program from crashing abruptly.

verakworld.com

1.6.1 Need for Exception Handling

Exception handling is used in Python and in other programming languages such as C++, Java and Ruby. It is a technique for capturing runtime errors and handling them so that the program does not crash.

Important Points

  • Python categorises exceptions into distinct types.
  • Specific exception handlers can be created for each type.
  • Exception handlers separate the main program logic from error detection and correction code.
  • Code where an exception may occur can be placed in one block.
  • Code for handling the exception can be placed in another block.
  • The compiler or interpreter keeps track of the exact position where the error occurred.
  • Both user-defined and built-in exceptions can be handled.
verakworld.com

1.6.2 Process of Handling Exception

Exception Object

When an error occurs, Python creates an object called the exception object. It contains information about the error, such as its type, file name and position in the program where the error occurred.

Throwing an Exception

The exception object is handed over to the runtime system so that it can find appropriate code to handle the particular exception. The process of creating an exception object and handing it over to the runtime system is called throwing an exception.

Call Stack

The runtime system searches the program for an exception handler. It first searches the method in which the error occurred. If it is not found, it searches the method from which that method was called. This reverse hierarchical search continues until an exception handler is found.

Call Stack: The entire list of methods involved in this search is known as the call stack.

Catching the Exception

When a suitable handler is found in the call stack, it is executed by the runtime process. This process of executing a suitable handler is known as catching the exception.

Logical Flow of the Textbook Process

Error occurs during program execution
Python creates an exception object
Exception object is handed to the runtime system
Runtime system searches the call stack for a suitable handler
Suitable handler found
Handler is executed → Exception is caught
No suitable handler found
Program execution stops
verakworld.com

Runtime System

The runtime system refers to the execution of statements in a program. It is a complex mechanism consisting of hardware and software that comes into action when a program written in a programming language is put into execution.

verakworld.com

1.6.3 Catching Exceptions

Definition: An exception is said to be caught when code designed to handle a particular exception is executed.

Exceptions are caught in the try block and handled in the except block.

Suspicious lines of code, where an exception may occur, are placed inside a try block. Every try block is followed by an except block.

Syntax of try…except
try:
    [program statements where exceptions might occur]
except [exception-name]:
    [code for exception handling if the exception-name error is encountered]
Program 1-2 — Using try…except Block
print ("Practicing for try block")
try:
    numerator=50
    denom=int(input("Enter the denominator"))
    quotient=(numerator/denom)
    print(quotient)
    print ("Division performed successfully")
except ZeroDivisionError:
    print ("Denominator as ZERO.... not allowed")
print("OUTSIDE try..except block")

Program Behaviour

  • If a non-zero denominator is entered, the quotient is displayed and the success message is displayed.
  • The except clause is skipped when there is no ZeroDivisionError.
  • If denominator is 0, execution of the try block stops.
  • Control moves to the except block.
  • The message about zero denominator is displayed.
  • The statement outside the try...except block is then executed.
verakworld.com

Multiple except Clauses

A single piece of code may have more than one possible type of error. Multiple except blocks can therefore be used with one try block.

Program 1-3 — Use of Multiple except Clauses
print ("Handling multiple exceptions")
try:
    numerator=50
    denom=int(input("Enter the denominator: "))
    print (numerator/denom)
    print ("Division performed successfully")
except ZeroDivisionError:
    print ("Denominator as ZERO is not allowed")
except ValueError:
    print ("Only INTEGERS should be entered")

Here, ZeroDivisionError and ValueError are handled using two except blocks for a single try block.

When an exception is raised, Python searches for a matching except block. If no match is found, the program terminates.

verakworld.com

except Without Specifying an Exception

If an exception occurs for which the programmer has not created a specific handler, an except clause without specifying an exception can be used.

This clause should be the last clause of the try...except block.

Program 1-4 — except Without Specifying an Exception
print ("Handling exceptions without naming them")
try:
    numerator=50
    denom=int(input("Enter the denominator"))
    quotient=(numerator/denom)
    print ("Division performed successfully")
except ValueError:
    print ("Only INTEGERS should be entered")
except:
    print(" OOPS.....SOME EXCEPTION RAISED")
Exam Point: The except clause without a specified exception is placed as the last except clause.
verakworld.com

1.6.4 try…except…else Clause

An optional else clause can be used along with the try...except clause.

  • If an exception occurs, the appropriate except block is executed.
  • If no error occurs, none of the except blocks is executed.
  • In the absence of an exception, statements inside the else clause are executed.
Program 1-5 — Use of else Clause
print ("Handling exception using try...except...else")
try:
    numerator=50
    denom=int(input("Enter the denominator: "))
    quotient=(numerator/denom)
    print ("Division performed successfully")
except ZeroDivisionError:
    print ("Denominator as ZERO is not allowed")
except ValueError:
    print ("Only INTEGERS should be entered")
else:
    print ("The result of division operation is ", quotient)
verakworld.com

1.7 Finally Clause

Definition: The finally clause contains statements that are always executed, regardless of whether an exception has occurred in the try block or not.

Important Points

  • finally is optional.
  • It is executed whether an exception occurs or not.
  • It is commonly used while working with files to ensure that the file object is closed.
  • If used, finally is placed at the end of the try clause.
  • It comes after all except blocks and the else block.
Program 1-6 — Use of finally Clause
print ("Handling exception using try...except...else...finally")
try:
    numerator=50
    denom=int(input("Enter the denominator: "))
    quotient=(numerator/denom)
    print ("Division performed successfully")
except ZeroDivisionError:
    print ("Denominator as ZERO is not allowed")
except ValueError:
    print ("Only INTEGERS should be entered")
else:
    print ("The result of division operation is ", quotient)
finally:
    print ("OVER AND OUT")

The message OVER AND OUT is displayed irrespective of whether an exception is raised or not.

verakworld.com

1.7.1 Recovering and Continuing with finally Clause

If an error is detected in the try block and the exception is thrown, the appropriate except block handles it.

If no except clause handles the exception, the exception is re-raised after the execution of the finally block.

Program 1-7 — Recovering through finally Clause
print (" Practicing for try block")
try:
    numerator=50
    denom=int(input("Enter the denominator"))
    quotient=(numerator/denom)
    print ("Division performed successfully")
except ZeroDivisionError:
    print ("Denominator as ZERO is not allowed")
else:
    print ("The result of division operation is ", quotient)
finally:
    print ("OVER AND OUT")

Behaviour of Program 1-7

If non-numeric data is entered, the finally block is executed and the message OVER AND OUT is displayed. Thereafter, the exception for which a handler is not present is re-raised.

After execution of the finally block, Python transfers control to a previously entered try or to the next higher level default exception handler.

Important: Unlike except, execution of the finally clause does not terminate the exception. The exception continues to be raised after execution of finally.
verakworld.com

Overall try…except…else…finally Structure

try
Code where an exception may occur
Exception occurs → matching except handler
If no exception occurs → else block
finally block → executed irrespective of exception
verakworld.com
Remember: The try block contains code where errors may occur, except blocks contain handlers, the optional else block executes when no exception occurs, and the optional finally block executes regardless of whether an exception occurs.
verakworld.com

Chapter Summary

  • Syntax errors or parsing errors occur when programming-language rules are not followed.
  • Python displays the name and a short description of a syntax error.
  • Program execution starts only after a syntax error is rectified.
  • An exception is a Python object representing an error.
  • Syntax errors are also handled as exceptions.
  • An exception needs to be handled so that the program does not terminate abruptly.
  • Python provides built-in exceptions for commonly occurring errors.
  • Common built-in exceptions include SyntaxError, ValueError, IOError, KeyboardInterrupt, ImportError, EOFError, ZeroDivisionError, IndexError, NameError, IndentationError, TypeError and OverFlowError.
  • Python raises or throws an exception when an error is encountered.
  • Exception handlers are codes designed to execute when a particular exception is raised.
  • Raising an exception interrupts normal program execution and transfers control to the exception handler.
  • raise and assert statements are used to raise exceptions.
  • Exception handling adds code that gives proper messages or instructions and prevents abrupt program crashing.
  • An exception is caught when the code designed to handle it is executed.
  • Exceptions are caught in the try block and handled in the except block.
  • Statements inside the finally block are always executed whether an exception occurs or not.
verakworld.com

Questions & Answers

1-Mark Questions

1. What is a syntax error?
A syntax error occurs when the rules of the programming language are not followed while writing a program. It is also called a parsing error.
2. What is an exception?
An exception is a Python object that represents an error.
3. What are built-in exceptions?
Commonly occurring exceptions defined in the compiler/interpreter are called built-in exceptions.
4. Name two statements used to raise exceptions.
The raise and assert statements.
5. Which exception is raised when the denominator is zero?
ZeroDivisionError.
6. Which block contains statements where exceptions might occur?
The try block.
7. Which block handles an exception?
The except block.
8. Which block executes when no exception occurs?
The optional else block.
9. Which block is always executed?
The finally block.
10. What is a call stack?
The entire list of methods searched in reverse hierarchical order for a suitable exception handler is known as the call stack.

2-Mark Questions

1. Distinguish between syntax errors and exceptions.
Syntax errors occur when programming-language rules are not followed. Other exceptions may occur during execution even when the statement or expression is syntactically correct.
2. What is the purpose of the raise statement?
The raise statement is used to throw an exception. It interrupts the normal flow of execution and transfers control toward exception handling.
3. Explain the use of the assert statement.
The assert statement tests an expression. If the expression is false, an AssertionError is raised. It is generally used to check valid input.
4. What is exception handling?
Exception handling is the process of writing additional code to give proper messages or instructions when an exception occurs and thereby prevent abrupt program crashing.
5. What is catching an exception?
An exception is said to be caught when the code designed to handle that particular exception is executed.

3-Mark Questions

1. Explain the process of handling an exception.
When an error occurs, Python creates an exception object containing information about the error. The object is handed to the runtime system. The runtime system searches for a suitable handler through the call stack. When a suitable handler is found, it is executed and the exception is caught. If no suitable handler is found, program execution stops.
2. Explain the need for exception handling.
Exception handling helps capture runtime errors and handle them without abrupt program termination. Python categorises exceptions into different types, allows specific handlers, separates main logic from error-handling code, tracks the error position, and supports both built-in and user-defined exceptions.
3. Explain multiple except clauses.
When a single piece of code may produce more than one type of error, multiple except clauses can be used with one try block. Python searches for the matching handler. If no match is found, the program terminates unless a general except clause is provided.

4/5-Mark Questions

1. Explain try, except, else and finally clauses.
The try block contains statements where exceptions might occur. The except block contains code to handle a matching exception. The optional else block executes when no exception occurs. The optional finally block executes regardless of whether an exception occurs or not.
2. Explain raising exceptions using raise and assert.
The raise statement is used to throw an exception and can include an optional argument. The assert statement tests an expression and raises AssertionError if the expression is false. Both are used to raise exceptions in a Python program.
verakworld.com

Important Difference Questions

Basis Syntax Error Exception
Meaning Occurs when programming-language rules are not followed. Represents an error that can occur during execution.
Program execution The program does not execute until the syntax error is rectified. The exception may disrupt normal execution and can be handled.
Example from chapter SyntaxError ZeroDivisionError, ValueError, IndexError and others.
Clause Purpose
try Contains code where an exception might occur.
except Contains code to handle an exception.
else Executes when no exception occurs.
finally Executes regardless of whether an exception occurs or not.
verakworld.com

📝 Important Questions

1 Mark

  1. Define syntax error.
  2. What is an exception?
  3. What is a built-in exception?
  4. Name two statements used for raising exceptions.
  5. What is ZeroDivisionError?
  6. What is ValueError?
  7. What is IndexError?
  8. What is NameError?
  9. What is the use of the finally block?

2 Marks

  1. Explain syntax errors and parsing errors.
  2. Explain the purpose of the raise statement.
  3. Explain the assert statement.
  4. Define exception handling.
  5. Define throwing and catching an exception.
  6. Explain the need for exception handling.

3 Marks

  1. Explain the process of handling an exception.
  2. Explain catching exceptions using try and except.
  3. Explain the use of multiple except clauses.
  4. Explain the purpose of the else clause.

4/5 Marks

  1. Explain built-in exceptions in Python with their meanings.
  2. Explain raising exceptions using raise and assert.
  3. Explain exception handling using try...except.
  4. Explain try...except...else with the program structure.
  5. Explain the finally clause and its behaviour when an exception is not handled.
  6. Write a suitable exception-handling program for division and handle the denominator being zero.
Board-Exam Focus: Give special attention to built-in exceptions, raise, assert, exception handling, try...except, multiple except clauses, else, finally, throwing/catching exceptions, and the process of searching the call stack.
verakworld.com

⚡ Quick Revision

Important Definitions

  • Syntax error
  • Exception
  • Built-in exception
  • Exception handling
  • Throwing an exception
  • Catching an exception
  • Call stack
verakworld.com

Important Terms

  • SyntaxError
  • ValueError
  • IOError
  • KeyboardInterrupt
  • ImportError
  • EOFError
  • ZeroDivisionError
  • IndexError
  • NameError
  • IndentationError
  • TypeError
  • OverFlowError
  • AssertionError
verakworld.com

Important Syntax

raise exception-name[(optional argument)]

assert Expression[,arguments]

try:
    [program statements]
except [exception-name]:
    [exception handling code]
verakworld.com

Important Clauses

  • try → possible exception code
  • except → exception handler
  • else → no exception
  • finally → always executed
verakworld.com

Important Programs

  • Use of assert statement
  • Using try...except
  • Multiple except clauses
  • Unnamed except clause
  • try...except...else
  • try...except...else...finally
  • Recovering through finally
verakworld.com

Important Flow

Error → Exception Object → Runtime System → Call Stack Search → Suitable Handler → Catch Exception

If no suitable handler is found → Program execution stops.

verakworld.com

Final Revision Section

Must Remember Before Examination

  1. Syntax errors occur when the rules of the programming language are not followed.
  2. An exception is a Python object representing an error.
  3. Built-in exceptions are commonly occurring exceptions defined in the compiler/interpreter.
  4. raise is used to throw an exception.
  5. assert tests an expression and raises AssertionError when the expression is false.
  6. Exception handling prevents abrupt program termination.
  7. The try block contains code where an exception may occur.
  8. The except block handles the matching exception.
  9. Multiple except blocks can handle different exception types.
  10. An unnamed except clause can handle an exception for which a specific handler has not been created and should be the last clause.
  11. The else block executes when no exception occurs.
  12. The finally block executes regardless of whether an exception occurs or not.
  13. If an exception is not handled by an except clause, it can continue to be raised after the finally block.
  14. The call stack is searched to find a suitable exception handler.
verakworld.com

Built-in Exceptions — One-Glance Revision

Exception Remember It As
SyntaxError Error in Python syntax
ValueError Correct data type but inappropriate value
IOError Specified file cannot be opened
KeyboardInterrupt Normal flow interrupted by user action described in the textbook
ImportError Requested module definition not found
EOFError End-of-file condition reached without data from input()
ZeroDivisionError Denominator is zero
IndexError Sequence index/subscript out of range
NameError Variable name not defined
IndentationError Incorrect indentation
TypeError Incorrect data type supplied to an operator
OverFlowError Calculation result exceeds numeric data-type limit
verakworld.com

Textbook Exercise — Exam Practice

  1. Justify the statement that every syntax error is an exception but every exception cannot be a syntax error.
  2. Explain when ImportError, IOError, NameError and ZeroDivisionError are raised, with suitable examples.
  3. Explain the use of the raise statement and prepare a program to accept two numbers and display their quotient, raising an appropriate exception when the denominator is zero.
  4. Use an assert statement in the division problem to test the division expression.
  5. Define exception handling, throwing an exception and catching an exception.
  6. Explain catching exceptions using try and except.
  7. Complete a program using the appropriate exceptions for accepting only integers, preventing a zero denominator, an else clause and a finally clause.
  8. Using the math module, prepare a program involving an incorrect number of arguments for a method such as sqrt() or pow() and apply exception handling as required by the textbook exercise.
  9. Explain the use of the finally clause and apply it to the division exception-handling problem.
verakworld.com

📝 This article was researched and written by Venkatesh A, Founder of verakworld.com.

Leave a Comment