Error Handling in Python – try except

Error Handling in Python – try except

In this video, we’ll delve into the intricacies of try…except blocks, handling specific exceptions like ZeroDivisionError or IndexError, and utilizing try with else.

What You’ll Learn:

  • try…except Block: Understand the basics of handling exceptions.
  • Handling Specific Exceptions: Learn how to manage specific errors like ZeroDivisionError and IndexError effectively.
  • Using try with else: Discover how to execute code when no exceptions are raised, making your programs more robust and error-proof.

Whether you’re a beginner or an experienced Python developer, mastering error handling is crucial.

Tutorial Video

Python Code

  • Error handling is a fundamental aspect of writing robust and reliable code.
  • As developers, we encounter unexpected situations—such as division by zero, out-of-bounds array access, or invalid input—more often than we’d like.
  • Python provides powerful tools to gracefully handle these exceptions and prevent our programs from crashing.

Basic Exception Handling:

  • In Python, we use the try…except block to handle exceptions.
  • The try block contains the potentially problematic code. If an exception occurs (like division by zero), the except block catches it and executes the specified statements
numerator   = 10
denominator = 0

try:
    # Code that may cause an exception
    numerator = 10
    denominator = 0
    result = numerator / denominator
    print(result)
except:
    # Code to run when an exception occurs
    print("Error: Denominator cannot be 0.")

Handling Specific Exceptions:

  • You can handle different exceptions differently using multiple except blocks.
  • In this case, we handle ZeroDivisionError and IndexError separately. If an index out of bounds occurs, the IndexError block is executed
try:
    even_numbers = [2, 4, 6, 8]
    print(even_numbers[5])  # Accessing index 5 (out of bounds)
except ZeroDivisionError:
    print("Denominator cannot be 0.")
except IndexError:
    print("Index Out of Bound.")

Using try with else:

  • Sometimes, we want to run code only if the try block runs without errors. The else keyword helps achieve this
  • If the input is an even number, the reciprocal is computed and displayed. Otherwise, the error message is shown
num = 3

try:
    assert num % 2 == 0  # Check if even
except:
    print("Not an even number!")
else:
    reciprocal = 1 / num
    print(reciprocal)

Example 1: Dividing two numbers

# Function to divide two numbers
def divide_numbers(num1, num2):
    try:
        result = num1 / num2
        return result
    except ZeroDivisionError as e:
        print(f"Error: {e} - Cannot divide by zero.")
    except TypeError as e:
        print(f"Error: {e} - Please provide valid numbers.")
    except Exception as e:
        print(f"Error: {e} - An unexpected error occurred.")

# Example usage of the divide_numbers function
print("Example 1: Dividing two numbers")
print(divide_numbers(10, 2))  
print(divide_numbers(10, 0))  
print(divide_numbers('10', 2))  

Example 2: Opening a file

# Function to divide two numbers
def divide_numbers(num1, num2):
    try:
        result = num1 / num2
        return result
    except ZeroDivisionError as e:
        print(f"Error: {e} - Cannot divide by zero.")
    except TypeError as e:
        print(f"Error: {e} - Please provide valid numbers.")
    except Exception as e:
        print(f"Error: {e} - An unexpected error occurred.")

# Example usage of the divide_numbers function
print("Example 1: Dividing two numbers")
print(divide_numbers(10, 2))  
print(divide_numbers(10, 0))  
print(divide_numbers('10', 2))