Exception Handling

Errors happen. A robust program handles errors gracefully instead of crashing. In Python, we use the try...except block for this.

1. Basic Try-Except

Wrap risky code in the try block and handle errors in the except block.

try:
    x = int(input("Enter a number: "))
    result = 10 / x
    print(f"Result: {result}")
except ZeroDivisionError:
    print("Error: Cannot divide by zero.")
except ValueError:
    print("Error: Please enter a valid integer.")

2. Raising Exceptions

You can force an error to occur using the raise keyword.

def check_age(age):
    if age < 0:
        raise ValueError("Age cannot be negative.")
    return age

3. Finally & Else

  • else: Runs if no exception occurred.
  • finally: Always runs, regardless of whether an exception occurred (useful for cleanup).
try:
    f = open("log.txt", "w")
    f.write("System check...")
except IOError:
    print("Writing failed")
else:
    print("Success") # Runs if no Error
finally:
    f.close() # Runs ALWAYS
Best Practice: Always catch specific exceptions. Avoid using a bare except: block as it can hide bugs by catching unexpected errors.