Sunday, December 3, 2023

Day 7: Error Handling and Exception Handling

Chapter 1: Understanding Errors in Python

Errors are a natural part of programming, and Python provides mechanisms to handle them gracefully. Errors can be broadly categorized into two types: syntax errors and runtime errors.

Syntax Errors

Syntax errors occur when the code violates the rules of the Python language. They are detected by the interpreter during the parsing of the code:

        
# Syntax error example
print("Hello, World"
        
    

This will result in a syntax error due to the missing closing parenthesis.

Runtime Errors

Runtime errors, also known as exceptions, occur during the execution of the code. They can be caused by various reasons, such as division by zero, attempting to access an undefined variable, or calling a method on an inappropriate data type:

        
# Runtime error example
result = 10 / 0  # Division by zero
        
    

This will result in a runtime error, specifically a ZeroDivisionError.

Chapter 2: Exception Handling in Python

Python provides a robust mechanism for handling exceptions using the try, except, else, and finally blocks.

try and except Blocks

Use the try block to enclose the code that might raise an exception. If an exception occurs, it is caught and handled in the corresponding except block:

        
# Exception handling with try and except
try:
    result = 10 / 0
except ZeroDivisionError as e:
    print(f"Error: {e}")
        
    

The code inside the except block is executed only if a ZeroDivisionError occurs.

else Block

The else block is executed if no exceptions are raised in the try block:

        
# Using else block in exception handling
try:
    result = 10 / 2
except ZeroDivisionError as e:
    print(f"Error: {e}")
else:
    print("Division successful!")
        
    

If no exception occurs, the code in the else block is executed.

finally Block

The finally block is always executed, regardless of whether an exception is raised or not. It is commonly used for cleanup operations:

        
# Using finally block in exception handling
try:
    result = 10 / 2
except ZeroDivisionError as e:
    print(f"Error: {e}")
else:
    print("Division successful!")
finally:
    print("This block always runs.")
        
    

The code in the finally block runs no matter what, making it suitable for tasks like closing files or releasing resources.

Chapter 3: Custom Exceptions

Python allows you to define custom exceptions by creating a new class that inherits from the built-in Exception class:

        
# Creating a custom exception
class MyCustomError(Exception):
    pass

# Using the custom exception
try:
    raise MyCustomError("This is a custom error.")
except MyCustomError as e:
    print(f"Caught an instance of MyCustomError: {e}")
        
    

Custom exceptions help you structure your code and handle specific error scenarios more effectively.

Chapter 4: Logging and Debugging

Logging is a crucial aspect of error handling. Python provides a built-in logging module that allows you to record messages from your program, providing insights into its execution:

        
# Using the logging module
import logging

logging.basicConfig(level=logging.DEBUG)

try:
    result = 10 / 0
except ZeroDivisionError as e:
    logging.error(f"Error: {e}", exc_info=True)
        
    

This logs the error message along with additional information like the traceback.

Debugging tools, such as pdb (Python Debugger), can also be employed to step through code, inspect variables, and identify the root cause of errors.

Understanding error handling is essential for writing robust and reliable Python programs. Stay tuned for Day 8, where we'll explore File Handling and Input/Output Operations.

If you have any questions or need further clarification, feel free to ask.

No comments:

Post a Comment

scala project to support JDK 17

Compiling my Scala project with JDK 17. status: the project once used sbt version 1.2.8 and scala 2.12.8, and targets JDK 11. it works fin...