Day 14: Error Handling in Python - Writing Robust Code
Sarasa Jyothsna Kamireddi
Aspiring Python Developer | Machine Learning Enthusiast | Experienced in Reliability Engineering
Errors are inevitable, but handling them properly prevents crashes and ensures smooth execution. Python provides powerful ways to handle exceptions gracefully.
1?? try-except - Catching Errors
Use try-except to handle errors without breaking the program
try:
result = 10/0
except ZeroDivisionError as e:
print(f"Error: {e}")
?? Best for: Handling specific exceptions
2?? try-except-else - Running Code Only if No Error
try:
num = int(input("Enter a number: "))
except ValueError:
print("Invalid input! Please enter a number:")
else:
print(f"You entered: {num}")
?? Best for: Running safe code only after error-free execution
3?? try-finally - Ensuring Cleanup
The finally block always executes, even if an error occurs
try:
file = open("data.txt", "r")
content = file.read()
finally:
file.close()
?? Best for: Releasing resources like file handles or database connections
4?? Raising Custom Exceptions
Use raise to create custom errors for better debugging
def check_age(age):
if age<18:
raise ValueError("Age must be 18 or above!")
return "Access granted"
print(check_age(15))
?? Best for: Enforcing business rules
Key Takeaways
?? Use try-except to catch errors and avoid crashes
?? Use else to run code when no error occurs
?? Use finally to ensure resource cleanup
?? Use raise for custom exceptions
#100DaysOfCode #Python #ErrorHandling #Exceptions