Day 14: Error Handling in Python - Writing Robust Code

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


To view or add a comment, sign in

More articles by Sarasa Jyothsna Kamireddi

Insights from the community

Others also viewed

Explore topics