Understanding try-except-finally blocks in Python
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.
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.")
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.")