Exception Handling in Python Notes – Class 12 CS (083)
Python Exception Handling Notes with simple explanations, practical examples, and CBSE-oriented content to help you prepare confidently for exams and practicals.
In this comprehensive Exception Handling in Python notes of Class 12 Computer Science (083), each topic is explained step by step with clear syntax, easy-to-understand explanations, and practical examples.
Error
- Errors are unwanted conditions in our program which occurs when:
- Programs abrupted abnormally
- Returns unexpected output
- Program is hanged
Types of Error
- Syntax Error
- Run time Error
- Logical Error
Syntax Error
- Also called parsing error and it occurs at compile time
- It occurs when code is not written according to programming rules
- Interpreter does not execute the program until the Syntax error is corrected, saved, and rerun.
- Syntax errors can appear in different working modes:
- Shell mode: Python shows the error name and displays a short description of the error.
- Script mode: A dialog box appears and shows name and small description of the error.
Runtime Error
- The program is syntactically correct but during execution:
- It may terminate abnormally Or
- it may get stuck/hang
- These errors occur due to invalid operations during execution (like division by zero, file not found, etc.).
- In Python, runtime errors are handled using Exception Handling.
Logical Error
- The program is syntactically correct but during execution:
- It produces unexpected or incorrect output
- These errors occur due to incorrect logic in the program.
- They are handled using debugging techniques.
Exception Handling in Python
What is Exception?
- Exceptions are python objects that represents an error which causes a program to abrupt abnormally during execution.
- An exception is said to be raised when an error occurs during program execution.
- A Syntax error is also an exception in Python.
- Examples: Type Error, Division by zero error, File not found error, Name error, Import error
Need for Exception Handling
- Exception handling helps in:
- Separating main program logic from error-handling code
- Keeping error detection and correction code in separate blocks
- Ensuring main program flow is not affected
Process of Handling Exception
- When an error occurs, the Python interpreter creates an exception object.
- The exception object is passed to the runtime system so that it can find appropriate code to handle the exception.
- This process of creating the exception object and passing it to the runtime system is called throwing an exception.
- When an exception occurs during execution of a program statement:
- Control immediately search and jumps to an exception handler
- Remaining program statements are not executed
- The runtime system searches the entire program for a suitable exception handler that can handle the raised exception.
- When a suitable handler is found:
- It is executed by the runtime system
- This process is called catching the exception
- If no appropriate handler is found after searching than:
- Program execution stops
- The program terminates abnormally
Built-In Exceptions
- Commonly occurring exceptions are defined in the compiler/interpreter and are called built-in exceptions.
- Python’s standard library provides a wide collection of built-in exceptions to handle commonly occurring errors.
| Exception Name | Explanation |
| SyntaxError | Raised when there is an error in the syntax of the Python code. |
| ValueError | Raised when a function gets correct data type but invalid value. |
| IOError | Raised when a file cannot be opened or accessed. |
| KeyboardInterrupt | Raised when user interrupts program execution using keys like Ctrl+C/Esc. |
| ImportError | Raised when a required module cannot be found. |
| EOFError | Raised when input() reaches end of file without reading data. |
| ZeroDivisionError | Raised when a number is divided by zero. |
| IndexError | Raised when an index is out of range in a sequence. |
| NameError | Raised when a variable is used but not defined. |
| IndentationError | Raised due to incorrect indentation in code. |
| TypeError | Raised when an operation is applied to an incorrect data type. |
| OverflowError | Raised when a calculation exceeds numeric limit. |
Catching Exceptions
- An exception is said to be caught when the code designed to handle it is executed.
- Exceptions are Placed inside a try block and Handled in an except block
- While writing or debugging a program:
- Suspicious code (where exception may occur) is placed inside the try block
- Every try block must be followed by at least one except block
- The except block contains code for handling the possible exception
- During execution:
- If an exception occurs, the remaining try block is skipped
- Control is transferred to the except block
- After handling program continues execution after the try–except block
Syntax of try–except
try:
# program statements where exceptions might occur
except exception-name:
# code to handle the exception
Example: Handling ZeroDivisionError in Python Program
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…. not allowed”)
print(“OUTSIDE try..except block”)
Working:
- If denominator is non-zero:
- Division is performed successfully
- except block is skipped
- final message is printed
- If denominator is zero:
- try block stops execution
- control moves to except blockerror message is displayed
- program continues after try–except block
Multiple Exceptions Handling
- A single try block may have multiple types of errors.
- To handle this:
- Multiple except blocks can be used
Example: 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”)
Working:
- If different exceptions occur:
- Python searches for matching except block
- If found, it is executed
- If not found, program terminates
Handling Unknown Exceptions
- Sometimes a programmer does not know all possible errors.
- In such cases:
- An except block without exception name is used
- It must be placed at the end of all except clauses
Example: Except without specifying 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”)
Working:
- If denominator is 0:
- ZeroDivisionError occurs
- No specific handler is found
- Final except block executes
- Message “OOPS…..SOME EXCEPTION RAISED” is displayed
try…except…else Clause
- An optional else clause can be used with the try…except block.
- The except block is executed only when an exception occurs in the try block.
- If no error occurs:
- None of the except blocks are executed
- The statements inside the else block are executed
Example: 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)
Working:
- If no exception occurs:
- Division is performed successfully
- else block executes and displays result
- If an exception occurs:
- Appropriate except block executes
- else block is skipped
Finally Clause
- The finally clause is an optional part of the try statement in Python.
- The statements inside the finally block are always executed:
- Whether an exception occurs or not
- It is commonly used when working with files to ensure that:
- The file is properly closed
- The finally block should always be placed:
- At the end of the try statement
- After all except blocks and the else block
Example: 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 always displayed, Whether an exception occurs or not.
Key Behavior of finally Block
- After execution of finally block:
- Control may move to a higher-level exception handler
- Or to the default exception handler
- Unlike except block:
- finally does not stop the exception
- The exception continues after finally execution
Raising Exceptions
- Whenever an error is detected in a program, the Python interpreter raises (throws) an exception.
- Exception handlers are designed to execute when a specific exception is raised.
- Programmers can also forcefully raise exceptions using:
- raise statement
- assert statement
The raise Statement
- The raise statement is used to explicitly throw an exception.
- Syntax:
raise exception-name[(optional argument)] - The optional argument is usually a string message and displayed when the exception occurs.
- The raised exception can be Built-in or user-defined
Example of raise statement
print(“Example of raise statement”)
age = int(input(“Enter your age: “))
if age < 18:
raise ValueError(“You are not eligible (age must be 18 or above)”)
print(“You are eligible”)
The assert Statement
- The assert statement is used to test an expression in a program.
- Syntax:
assert Expression[, arguments] - Python evaluates the expression:
- If True → program continues normally
- If False → AssertionError is raised
- It is commonly used:
- At the beginning of a function
- After a function call
- To ensure valid input
Example: 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))
Working:
- If number is positive:
- Function executes normally
- If number is negative:
- AssertionError is raised
- Message “OOPS… Negative Number” is displayed
- Remaining statements are not executed