Exception Handling in Python (Class XII Computer Science)
1. Introduction to Exceptions
In Python, errors can be broadly classified into two categories:
- Syntax Errors: Mistakes in the construction of the code (e.g., missing colons, misspelled keywords). These are detected by the compiler/interpreter before the program executes.
- Exceptions: Errors detected during execution (runtime). Even if a program is syntactically correct, it may cause an error during execution due to unexpected conditions or inputs.
Definition: An Exception is an abnormal event or error that occurs during the execution of a program and disrupts its normal flow.
Common Built-in Exceptions in Python:
ZeroDivisionError: Raised when a number is divided by zero.ValueError: Raised when a function receives an argument of the correct type but an inappropriate value (e.g.,int("abc")).TypeError: Raised when an operation or function is applied to an object of an inappropriate type (e.g., adding a string to an integer).IndexError: Raised when a sequence subscript (index) is out of range.KeyError: Raised when a dictionary key is not found.FileNotFoundError: Raised when an input file cannot be found in the specified path.
2. Need for Exception Handling
If an exception is not handled, the program terminates abruptly, and Python prints a traceback message. In real-world applications, sudden crashes are unacceptable.
Exception Handling allows a program to detect errors, handle them gracefully, and continue executing the remaining code without crashing.
3. Handling Exceptions Using try-except-finally
Python provides a powerful mechanism to catch and handle exceptions using four keywords: try, except, else, and finally.
A. The try block
- Contains the block of code that might raise an exception.
- Python executes this block first. If an error occurs, execution of the
tryblock stops immediately, and control shifts to theexceptblock.
B. The except block
- Contains the code that executes only if an exception occurs in the
tryblock. - You can specify the exact exception you want to catch, or use a general
exceptblock to catch all errors.
Example (Catching a specific exception):
Python
try:
num1 = int(input("Enter numerator: "))
num2 = int(input("Enter denominator: "))
result = num1 / num2
print("Result is:", result)
except ZeroDivisionError:
print("Error: You cannot divide a number by zero!")
except ValueError:
print("Error: Please enter valid integers only!")
print("Program continues executing...")
C. The else block (Optional)
- Code inside the
elseblock executes only if no exceptions were raised in thetryblock. - It must be placed after the
exceptblocks.
Example with else:
Python
try:
num = int(input("Enter an even number: "))
assert num % 2 == 0
except AssertionError:
print("That is not an even number!")
else:
print("Thank you! You entered a valid even number.")
D. The finally block
- Code inside the
finallyblock always executes, regardless of whether an exception occurred or was handled. - It is typically used for clean-up actions, such as closing a file, disconnecting from a database, or releasing system resources.
Example demonstrating try-except-finally:
Python
try:
file = open("sample.txt", "r")
content = file.read()
print(content)
except FileNotFoundError:
print("Error: The file does not exist.")
finally:
print("Executing finally block: Cleaning up resources.")
# If the file was successfully opened, close it
if 'file' in locals() and not file.closed:
file.close()
print("File closed successfully.")
Summary Table of Block Behavior
| Block Name | When does it execute? | Mandatory / Optional |
try | Always executes first. | Mandatory |
except | Only if an error/exception occurs in the try block. | Mandatory (at least one except or finally must follow try) |
else | Only if no error occurs in the try block. | Optional |
finally | Always executes, whether an error occurred or not. | Optional |
Quick Review Questions for Board Exams
- What is the difference between a Syntax Error and an Exception?
- Answer: Syntax errors occur when the rules of the language are violated and are caught during compilation/interpretation. Exceptions occur during runtime when the code is syntactically correct but encounters an unexpected execution state (e.g., division by zero).
- Can we have a
tryblock without anexceptblock?- Answer: Yes, but only if it is accompanied by a
finallyblock. Atryblock must be followed by either anexceptblock, afinallyblock, or both.
- Answer: Yes, but only if it is accompanied by a
- What is the significance of the
finallyblock?- Answer: The
finallyblock defines clean-up actions that must be executed under all circumstances (even if the program crashes or encounters areturnstatement), making it ideal for closing files or network connections.
- Answer: The