HOME HTML EDITOR C JAVA PHP python

Python Try...Except

Exception handling in Python lets you catch and handle runtime errors gracefully so your program does not crash unexpectedly. You test risky code inside a try block and handle errors inside an except block.

1. Basic try and except

If an error occurs inside the try block, execution jumps immediately to the matching except block:

try:
    result = 10 / 0
    print(result)
except ZeroDivisionError:
    print("Error: Cannot divide by zero.")

2. Handling Multiple Exceptions

You can catch different error types separately to give specific, helpful messages:

raw_input = "abc"

try:
    number = int(raw_input)
    print(100 / number)
except ValueError:
    print("Please enter a valid integer.")
except ZeroDivisionError:
    print("Number cannot be zero.")

3. Using else and finally

The else block runs only when no exception occurs in try, while the finally block runs whether an error happened or not (great for cleanup):

try:
    val = int("25")
except ValueError:
    print("Invalid conversion")
else:
    print("Converted successfully:", val)
finally:
    print("Execution block finished.")

4. Raising Exceptions with raise

Use the raise keyword to trigger an exception manually when a condition violates your rules:

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

try:
    set_age(-5)
except ValueError as err:
    print("Caught error:", err)
Tip: Catch specific exceptions like ValueError or KeyError rather than bare except: whenever possible so you do not hide unexpected bugs.