In Python, error handling is done using exception handling with try
, except
, and finally
blocks. This allows you to catch and handle runtime errors without stopping the entire program. Here's how you can do it:
1. Basic Syntax:
try:
# Code that might throw an exception
x = 10 / 0
except ZeroDivisionError:
# Handling the exception
print("You can't divide by zero!")
2. Handling Multiple Exceptions:
You can handle different types of exceptions in one block.
try:
num = int(input("Enter a number: "))
result = 10 / num
except ZeroDivisionError:
print("You can't divide by zero!")
except ValueError:
print("Invalid input! Please enter a number.")
3. Using finally
to Execute Cleanup Code:
The finally
block runs regardless of whether an exception occurred or not. This is useful for cleaning up resources like closing files or network connections.
try:
file = open("sample.txt", "r")
# Process file content
except FileNotFoundError:
print("File not found.")
finally:
file.close() # Ensures the file is always closed
4. Catching All Exceptions:
While it's generally a good idea to catch specific exceptions, you can use a generic except
block to catch all exceptions. However, this should be done cautiously.
try:
# Some risky operation
result = 10 / 0
except Exception as e:
print(f"An error occurred: {e}")
Pro Tip:
It's best practice to handle exceptions at a granular level. Instead of using a generic except
, try to be specific about the errors you expect. This will help in debugging and make your code more readable and maintainable.
If you're new to Python or looking for more advanced tutorials, check out Vtuit—an excellent platform offering courses, tutorials, and resources to master Python programming and much more. Whether you're a beginner or an advanced developer, you'll find valuable learning content to help you grow. Happy coding!
Top comments (0)