Exception Handling

Exception Handling in Python (Class XII Computer Science)

1. Introduction to Exceptions

In Python, errors can be broadly classified into two categories:

  1. 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.
  2. 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 try block stops immediately, and control shifts to the except block.

B. The except block

  • Contains the code that executes only if an exception occurs in the try block.
  • You can specify the exact exception you want to catch, or use a general except block 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 else block executes only if no exceptions were raised in the try block.
  • It must be placed after the except blocks.

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 finally block 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 NameWhen does it execute?Mandatory / Optional
tryAlways executes first.Mandatory
exceptOnly if an error/exception occurs in the try block.Mandatory (at least one except or finally must follow try)
elseOnly if no error occurs in the try block.Optional
finallyAlways executes, whether an error occurred or not.Optional

Quick Review Questions for Board Exams

  1. 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).
  2. Can we have a try block without an except block?
    • Answer: Yes, but only if it is accompanied by a finally block. A try block must be followed by either an except block, a finally block, or both.
  3. What is the significance of the finally block?
    • Answer: The finally block defines clean-up actions that must be executed under all circumstances (even if the program crashes or encounters a return statement), making it ideal for closing files or network connections.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top