HTML

    Select a Subtopic

    Day 7: Exception Handling

    Let's dive into Day 7 of your Python learning schedule, which is all about Exception Handling.

    Topics:

    • Try-Except Blocks: Python uses try-except blocks to handle errors gracefully, so your program doesn't crash when an error occurs.
    • Finally Clause: The `finally` block is always executed, whether an exception occurred or not.
    • Custom Exceptions: You can define your own exceptions by inheriting from the `Exception` class.

    1. Try-Except Blocks

    Python uses try-except blocks to handle errors gracefully. A basic structure looks like this:

    try: # code that may cause an error except SomeException: # code that runs if an exception occurs

    2. Finally Clause

    The `finally` block is always executed, whether an exception occurred or not. It's often used to clean up resources, like closing files or releasing network connections.

    try: # code except SomeException: # handle exception finally: # always runs, whether exception occurs or not

    3. Custom Exceptions

    You can define your own exceptions by inheriting from the `Exception` class. Here's an example:

    class CustomError(Exception): pass try: raise CustomError("Something went wrong!") except CustomError as e: print(f"Caught custom exception: {e}")

    Exercises:

    Exercise 1: Handle Division by Zero

    Write a program that takes two numbers as input and performs division. Use exception handling to catch division by zero and print a friendly message.

    def divide_numbers(): try: num1 = float(input("Enter the first number: ")) num2 = float(input("Enter the second number: ")) result = num1 / num2 print(f"The result is: {result}") except ZeroDivisionError: print("Error: Cannot divide by zero.") except ValueError: print("Error: Please enter valid numbers.") finally: print("Execution completed.") divide_numbers()

    Exercise 2: Custom Exception for Invalid Input

    Create a custom exception that is raised when a user enters a number less than zero. Handle it gracefully using a try-except block.

    class NegativeNumberError(Exception): """Custom exception for negative numbers.""" pass def check_number(): try: num = float(input("Enter a positive number: ")) if num < 0: raise NegativeNumberError("Negative numbers are not allowed!") print(f"Valid number: {num}") except NegativeNumberError as e: print(f"Error: {e}") except ValueError: print("Error: Please enter a valid number.") finally: print("Thank you for using the program.") check_number()

    Additional Concepts:

    • Catching Multiple Exceptions: You can catch multiple exceptions in a single `except` block.
    • Raising Exceptions: You can raise exceptions intentionally using the `raise` keyword.
    • The `else` Clause: If no exception occurs, the `else` block will be executed.

    Summary of Key Points:

    • Try-Except: Blocks allow you to catch and handle exceptions without crashing the program.
    • Finally: The `finally` block ensures code always runs, regardless of exceptions.
    • Custom exceptions: Define specific error types for your programs.
    • Raise: Exceptions manually when needed.

    Would you like to go over any specific part of this topic in more detail or work on additional exercises?