Python Exception Handling

Understanding try-except-finally blocks in Python

๐Ÿ“Œ What is Exception Handling?

Exception Handling allows your program to deal with unexpected errors gracefully, without crashing. Common errors like dividing by zero, accessing unavailable files, or invalid user input can be caught and managed using try, except, and finally.

๐Ÿ’ก Keywords Explained:

๐Ÿงช Example:

try:
    num = int(input("Enter a number: "))
    result = 100 / num
    print("Result:", result)

except ZeroDivisionError:
    print("You can't divide by zero!")

except ValueError:
    print("Please enter a valid number!")

finally:
    print("This block runs no matter what.")

๐Ÿ” Breakdown:

๐Ÿ› ๏ธ Use Cases

๐Ÿ“Ž Real World Example (File Handling):

try:
    with open("data.txt", "r") as file:
        content = file.read()
        print(content)

except FileNotFoundError:
    print("The file doesn't exist.")

finally:
    print("Execution completed.")