Sunday, June 11, 2023

Chapter 10: Error Handling and Exceptions


 

10.1 Introduction to Errors and Exceptions

10.1.1 Understanding errors and exceptions in Python

Explanation: Errors and exceptions are part of the normal execution flow in Python. They occur when something goes wrong during the program's execution, and they can be handled to prevent program termination.

Example:

 

python

///Example

# ZeroDivisionError: division by zero

result = 1 / 0

10.1.2 Common types of built-in exceptions

Explanation: Python provides various built-in exception types to handle specific types of errors, such as ValueError, TypeError, and FileNotFoundError. Each exception type represents a specific error condition.

Example:

 

python

///Example

# ValueError: invalid literal for int() with base 10: 'abc'

number = int('abc')

10.1.3 The try-except block

Explanation: The try-except block allows for the handling of exceptions. Code that may raise an exception is placed within the try block, and the desired exception handling is specified in the except block.

Example:

 

python

///Example

try:

    result = 1 / 0

except ZeroDivisionError:

    print("Error: Division by zero occurred")

10.2 Handling Exceptions

10.2.1 Handling specific exceptions

Explanation: Specific exceptions can be caught and handled individually using multiple except blocks, allowing for different handling strategies based on the specific exception type.

Example:

 

python

///Example

try:

    result = 1 / 0

except ZeroDivisionError:

    print("Error: Division by zero occurred")

except ValueError:

    print("Error: Invalid value encountered")

10.2.2 Handling multiple exceptions

Explanation: Multiple exceptions can be handled using a single except block by specifying multiple exception types within parentheses.

Example:

 

python

///Example

try:

    result = int('abc')

except (ValueError, TypeError):

    print("Error: Invalid value encountered")

10.2.3 Handling all exceptions

Explanation: An except block without an explicitly specified exception type can be used to handle any exception that occurs within the try block. It allows for a generic exception handling strategy.

Example:

 

python

///Example

try:

    result = 1 / 0

except:

    print("An error occurred")

10.3 The else and finally Blocks

10.3.1 The else block

Explanation: The else block is executed if no exceptions occur within the try block. It provides a way to specify code that should run only if the try block completes without raising an exception.

Example:

 

python

///Example

try:

    result = 10 / 2

except ZeroDivisionError:

    print("Error: Division by zero occurred")

else:

    print("Result:", result)

10.3.2 The finally block

Explanation: The finally block is always executed, regardless of whether an exception occurred or not. It is commonly used to release resources or perform cleanup operations.

Example:

 

python

///Example

file = open("file.txt", "r")

try:

    content = file.read()

    print(content)

except:

    print("An error occurred")

finally:

    file.close()

10.4 Raising Exceptions

10.4.1 Raising exceptions manually

Explanation: Exceptions can be raised manually using the raise statement. It allows for the creation and raising of custom exceptions to indicate specific error conditions.

Example:

 

python

///Example

def divide(a, b):

    if b == 0:

        raise ValueError("Division by zero")

    return a / b

 

try:

    result = divide(1, 0)

except ValueError as e:

    print("Error:", str(e))

10.4.2 Creating custom exception classes

Explanation: Custom exception classes can be created by inheriting from the built-in Exception class. This allows for the creation of custom exception hierarchies to handle specific types of errors.

Example:

 

python

///Example

class CustomException(Exception):

    pass

 

try:

    raise CustomException("Custom exception occurred")

except CustomException as e:

    print("Error:", str(e))

0 comments:

Post a Comment