Python Tutorial (6) Exception Handling

Python Tutorial 6

What is Exception Handling in Python with Example

Exception handling in Python is a mechanism that allows you to gracefully handle errors or exceptional situations that may occur during the execution of a program. It helps prevent a program from crashing and provides a way to deal with errors in a controlled manner. In Python, exceptions are raised when an error occurs, and you can use the try, except, else, and finally blocks to handle these exceptions.

Here’s a basic example of exception handling in Python:

try:

    # Code that may raise an exception

    num1 = int(input(“Enter a numerator: “))

    num2 = int(input(“Enter a denominator: “))

    result = num1 / num2

except ZeroDivisionError:

    # Handle division by zero exception

    print(“Error: Division by zero is not allowed.”)

except ValueError:

    # Handle invalid input exception (e.g., entering a non-integer)

    print(“Error: Please enter valid integers.”)

else:

    # This block is executed if no exception is raised

    print(“The result of the division is:”, result)

finally:

    # This block is always executed, regardless of whether an exception occurred or not

    print(“This block is always executed.”)

In this example:

The try block contains the code that may raise an exception. In this case, it involves taking user input for two numbers, performing a division, and storing the result.

The except block is used to catch specific exceptions. Here, ZeroDivisionError is caught if the user enters 0 as the denominator, and ValueError is caught if the user enters a non-integer.

The else block is executed if no exceptions are raised in the try block. It prints the result of the division.

The finally block is always executed, whether an exception occurred or not. It is typically used for cleanup operations or releasing resources.

This is a simple example, and in a real-world scenario, you might encounter various types of exceptions and handle them accordingly. The goal is to ensure that your program can handle unexpected situations without crashing and can provide meaningful feedback to the user or log relevant information for debugging.

How to use Exception handling in python

Exception handling in Python is implemented using the try, except, else, and finally blocks. Here’s a general structure of how to use exception handling in Python:

try:

    # Code that may raise an exception

    # …

except SomeExceptionType as e:

    # Code to handle the exception of type SomeExceptionType

    # …

except AnotherExceptionType as e:

    # Code to handle the exception of type AnotherExceptionType

    # …

else:

    # Code to be executed if no exception is raised in the try block

    # …

finally:

    # Code to be executed whether an exception is raised or not

    # …

Let’s break down each part:

try block: This is the block where you place the code that may raise an exception.

except block(s): These blocks are used to catch and handle specific exceptions. You can have multiple except blocks to handle different types of exceptions. If any of the exceptions listed in the except blocks occur in the try block, the corresponding except block is executed.

else block: This block is optional and is executed only if no exceptions are raised in the try block. It contains code that should run when the try block is successful.

finally block: This block is also optional and is always executed, regardless of whether an exception occurred or not. It is typically used for cleanup operations, such as closing files or releasing resources.

Here’s a simple example:

try:

    x = int(input(“Enter a number: “))

    result = 10 / x

    print(“Result:”, result)

except ValueError:

    print(“Error: Please enter a valid number.”)

except ZeroDivisionError:

    print(“Error: Cannot divide by zero.”)

else:

    print(“No exceptions were raised.”)

finally:

    print(“This block always executes.”)

In this example, if the user enters a non-integer or 0, the corresponding except block will be executed. If the user enters a valid number, the else block will be executed, and the finally block will always execute at the end.

Where we use Exception handling in python?

Exception handling in Python is used in situations where there might be errors or unexpected behaviors that could occur during the execution of a program. Here are some common scenarios where exception handling is beneficial:

User Input:

When taking user input, you should anticipate that users might enter invalid data. Using exception handling ensures that your program doesn’t crash if the input is not what you expect.

try:

    num = int(input(“Enter a number: “))

except ValueError:

    print(“Invalid input. Please enter a valid number.”)

File Operations:

When reading from or writing to files, exceptions may occur if the file is not found, permissions are insufficient, or the file format is not as expected.

try:

    with open(“example.txt”, “r”) as file:

        content = file.read()

except FileNotFoundError:

    print(“File not found. Please check the file path.”)

Networking:

When working with network connections, exceptions might occur due to issues like network errors or unreachable servers.

import requests

try:

    response = requests.get(“https://example.com”)

    response.raise_for_status()  # Raise an exception for HTTP errors

except requests.RequestException as e:

    print(f”An error occurred: {e}”)

Database Operations:

When interacting with databases, exceptions may occur due to connection issues, SQL syntax errors, or unexpected data.

import sqlite3

try:

    conn = sqlite3.connect(“example.db”)

    cursor = conn.cursor()

    cursor.execute(“SELECT * FROM non_existent_table”)

except sqlite3.Error as e:

    print(f”Database error: {e}”)

finally:

    conn.close()

Mathematical Operations:

Exception handling can be useful when performing mathematical operations that may result in errors, such as division by zero.

try:

    result = 10 / 0

except ZeroDivisionError:

    print(“Error: Division by zero is not allowed.”)

API Calls:

When making API calls, exceptions can occur due to network issues, authentication problems, or unexpected API responses.

import requests

try:

    response = requests.get(“https://api.example.com/data”)

    response.raise_for_status()

    data = response.json()

except requests.RequestException as e:

    print(f”API request failed: {e}”)

By incorporating exception handling in these scenarios, you can make your code more robust and ensure that it gracefully handles errors, providing a better user experience and making debugging and maintenance easier.

What is Exception handling read write open in python with example?

Exception handling is commonly used when working with file operations, such as reading, writing, or opening files. Here’s an example that demonstrates exception handling with file operations in Python:

Reading from a File:

try:

    with open(“example.txt”, “r”) as file:

        content = file.read()

        print(“File content:”, content)

except FileNotFoundError:

    print(“Error: The specified file was not found.”)

except IOError as e:

    print(f”Error reading the file: {e}”)

In this example:

The open(“example.txt”, “r”) statement attempts to open a file named “example.txt” for reading (“r” mode).

The with statement ensures that the file is properly closed after reading its content.

The except FileNotFoundError block catches the exception if the specified file is not found.

The except IOError as e block catches other input/output errors (e.g., permission issues, file is a directory, etc.).

Writing to a File:

try:

    with open(“output.txt”, “w”) as file:

        file.write(“Hello, World!”)

except IOError as e:

    print(f”Error writing to the file: {e}”)

In this example:

The open(“output.txt”, “w”) statement attempts to open a file named “output.txt” for writing (“w” mode). If the file doesn’t exist, it will be created. If it does exist, its content will be truncated.

The with statement ensures that the file is properly closed after writing to it.

The except IOError as e block catches input/output errors that may occur during the writing process.

These examples showcase how exception handling can be used to gracefully handle file-related issues. Keep in mind that the specific exceptions you catch may vary based on the context and potential issues that could arise during file operations.

Leave a Reply