Exception Handling in Python

Here students of class 12 will learn about the  Exception Handling in Python. These notes are made to help the students in their board preparation. The topic  Exception Handling is introduced by the CBSE for the session 2023-24 onward. 

Errors

Errors in a program can be categorized into following types:

1. Compile Time Error: Errors that occur during the compilation of the program.

2. Run Time Error: Errors that occur while the program is running. Some of the example of run time error are:

  • Division by Zero
  • Using of undefined variable
  • Trying to access a non existing file

3. Logical Error: Errors in the program’s logic, which do not produce errors but lead to incorrect results. Some of the example of logical error are:

  • Giving wrong operator precedence
  • using wrong variable name for calculation

 

4. Syntax Errors: Mistakes in writing code that prevent the program from running. Some of the example of syntax error are:

  • Incorrect Indentation
  • Misspelled a keyword
  • leaving out a symbol such as colon (:), parentheses [{()}] or comma (,).

5. Semantics Errors: Logic errors that produce unintended results.

 

Exception Handling in Python

 Exception

– An exception is a type of error that occurs during program execution.

– Python generates an exception whenever an error is encountered.

– Exceptions can be handled to prevent the program from crashing.

 

 Error vs. Exception

– Error: Any mistake or issue in the code.

– Exception: An unexpected situation or error during program execution.

 

 Exception Handling

– Exception handling is the process of dealing with run-time errors.

– It involves using `try…except` blocks to catch and handle exceptions.

 

Program without Exception Handling

Python Program to divide two numbers without exception handling

num1 = int(input("Enter first number"))

num2 = int(input("Enter Second number"))

result = num1 / num2

print("Result:", result)

 

Output:

Exception Handling in Python Class 12 Notes

Exception Handling in Python Class 12 Notes

 

Program with Exception Handling

Python Program to divide two numbers with exception handling

num1 = int(input("Enter first number"))

num2 = int(input("Enter Second number"))

try:
    result = num1 / num2

    print("Result:", result)


except ZeroDivisionError:

    print ("You Can not divide a number by Zero....")

 

Exception Handling in Python Class 12 Notes

Exception Handling in Python

 Built-in Exceptions in Python

– Python provides various built-in exceptions that can be caught and handled using `try…except`.

 

In Python, exceptions are a way to handle runtime errors and exceptional situations that can occur during program execution. Python provides a variety of built-in exceptions that you can use to catch and handle different types of errors. Here are some of the most commonly used built-in exceptions in Python:

1. `SyntaxError`: Raised when there is a syntax error in your code.

2. `IndentationError`: Raised when there is an indentation error in your code, such as mismatched indentation levels.

3. `NameError`: Raised when a local or global name is not found.

4. `TypeError`: Raised when an operation or function is applied to an object of inappropriate type.

5. `ValueError`: Raised when an operation or function receives an argument of the correct type but an inappropriate value.

6. `KeyError`: Raised when a dictionary is accessed with a key that doesn’t exist.

7. `IndexError`: Raised when trying to access an element at an invalid index in a sequence (e.g., list, tuple).

8. `FileNotFoundError`: Raised when trying to open or manipulate a file that does not exist.

9. `IOError`: Raised for I/O-related errors, such as when reading or writing to a file fails.

10. `ZeroDivisionError`: Raised when attempting to divide by zero.

11. `AttributeError`: Raised when an attribute reference or assignment fails.

12. `ImportError`: Raised when an import statement fails to find the module.

13. `TypeError`: Raised when an incorrect type is passed as an argument to a function or method.

14. `AssertionError`: Raised when an `assert` statement fails.

15. `KeyboardInterrupt`: Raised when the user interrupts the program (e.g., by pressing Ctrl+C).

16. `EOFError`: Raised when an input operation reaches the end of the file.

17. `ArithmeticError`: A base class for numeric errors, including `ZeroDivisionError` and `OverflowError`.

18. `FileExistsError`: Raised when trying to create a file or directory that already exists.

19. `FileNotFoundError`: Raised when trying to access a file or directory that does not exist.

20. `PermissionError`: Raised when trying to perform an operation without the necessary permissions.

 

Handling Multiple Exceptions

In Python, you can handle multiple exceptions in the same program by using multiple except blocks within a try block. Each except block is responsible for handling a specific type of exception.

Here’s an example that demonstrates how to handle different exceptions:

def divide_numbers(a, b):
    try:
        result = a / b
    except ZeroDivisionError:
        print("Error: Division by zero!")
        result = None
    except ValueError:
        print("Error: Invalid input value!")
        result = None
    except TypeError:
        print("Error: Invalid data type!")
        result = None
    except Exception as e:
        print(f"An unexpected error occurred: {e}")
        result = None
    finally:
        print("Exception Handing in Python...")
    
    return result

# Example 1: Division without error
result1 = divide_numbers(10, 2)
print("Result 1:", result1)

# Example 2: Division by zero (ZeroDivisionError)
result2 = divide_numbers(5, 0)
print("Result 2:", result2)

# Example 3: Invalid input value (ValueError)
result3 = divide_numbers(10, "2")
print("Result 3:", result3)

# Example 4: Invalid data type (TypeError)
result4 = divide_numbers("10", 2)
print("Result 4:", result4)

 

Output:

Handling Multiple Exceptions

In this example, we have a divide_numbers function that performs division and handles multiple exceptions:

ZeroDivisionError is raised when attempting to divide by zero.
ValueError is raised if the input values cannot be converted to numeric types.
TypeError is raised if the data types of the input values are incompatible with division.
The generic Exception block is used to catch any unexpected exceptions and display an error message.
Each exception type is handled separately, allowing the program to provide appropriate error messages and perform cleanup operations for each case.

 

Exception Handling in Python

 The `finally` Block

– The `finally` block contains code that must execute, whether or not an exception was raised in the `try` block.

– It ensures that certain actions are taken regardless of the outcome.

 

In Python, the finally block is an essential part of exception handling, working alongside the try and except blocks. It allows you to define code that will execute regardless of whether an exception is raised or not. This can be particularly useful for tasks such as closing files, releasing resources, or performing cleanup operations to ensure that your program remains in a consistent state.

 

Here’s the basic structure of a try…except…finally block in Python:

try:
    # Code that may raise an exception
    # ...
except SomeException:
    # Handle the exception if it occurs
    # ...
finally:
    # Code that always runs, whether an exception occurred or not
    # ...

 

Finally Block Example

def divide_numbers(a, b):
    try:
        result = a / b
    except ZeroDivisionError:
        print("Error: Division by zero!")
        result = None
    finally:
        print("Notes Exception Handling in Python Class 12...")
        # This code will always run, even if an exception occurred or not
    
    return result

# Example 1: Division without error
result1 = divide_numbers(10, 2)
print("Result 1:", result1)

# Example 2: Division by zero (error)
result2 = divide_numbers(5, 0)
print("Result 2:", result2)

Output:

Exception Handling in Python Class 12 Notes

 

In this example, the divide_numbers function attempts to divide two numbers. If a ZeroDivisionError occurs (division by zero), it is caught in the except block. However, the finally block is executed in both cases to perform cleanup operations.

Here are some key points to remember about the finally block in Python exception handling:

The finally block is optional but useful for ensuring that critical cleanup operations are performed, even in the presence of exceptions.

The code inside the finally block will run regardless of whether an exception is raised or not. It is guaranteed to execute.

You can use the finally block to close files, release resources, or perform any other necessary cleanup tasks.

If there is a return statement in the finally block, it will override any return value set in the try or except blocks. So, be cautious when using return within the finally block.

 

 

Exception Handling in Python

 Raising/Forcing an Exception

– You can raise exceptions manually using the `raise` keyword.

– Syntax: `raise <exception>(<message>)` (The exception should be a pre-defined built-in exception.)

 

 Benefits of Exception Handling

– Exception handling separates error-handling code from normal code.

– It enhances code readability and clarity.

– It promotes consistent error-handling practices.

– It leads to clear, robust, and fault-tolerant programs.

 

Exception Handling in Python

 File Operations

 `seek()`

– Used to change the position of the file pointer to a specific location.

– The file pointer is like a cursor indicating where data should be read or written in the file.

– Syntax: `f.seek(file_location)` or `f.seek(offset, from_what)`

  – `0`: Sets the reference point at the beginning of the file (default).

  – `1`: Sets the reference point at the current file position.

  – `2`: Sets the reference point at the end of the file.

 

 `tell()`

– Tells the current position of the file pointer.

– In ‘r’ and ‘w’ mode, the file pointer is at the beginning of the file.

– In ‘a’ mode, the file pointer is at the end of the file when using `tell()`.

By cbsepython

A complete solution for the students of class 9 to 12 having subject Information Technology (402), Computer Science (083). Explore our website for all the useful content as Topic wise notes, Solved QNA, MCQs, Projects and Quiz related to the latest syllabus.

Copywrite © 2020-2024, CBSE Python,
All Rights Reserved