September 16, 2024

Tirth's Blog

My technical notes

Python Error Handling: try, except, and finally

1 min read

Error handling is crucial for building robust Python programs. Python provides mechanisms to handle exceptions using `try`, `except`, and `finally` blocks.

**Using try and except**
The `try` block contains code that may raise an exception, and the `except` block handles the exception:

try:
result = 10 / 0
except ZeroDivisionError:
print(“Cannot divide by zero!”)

**Using finally**
The `finally` block, if present, will execute no matter what, even if an exception is raised:

try:
file = open(“file.txt”, “r”)
except IOError:
print(“File not found!”)
finally:
file.close()

**Example**:

try:
number = int(input(“Enter a number: “))
except ValueError:
print(“Invalid input! Please enter a number.”)

**Conclusion**
Proper error handling ensures your program can gracefully handle unexpected situations and continue running smoothly.

Copyright © All rights reserved. | Newsphere by AF themes.