🐍 Try / Except (Error Handling)

errors

Good to know

⭐️ try/except prevents your program from crashing when errors occur. Use it when something might fail: file access, user input, conversions, network calls, etc. Always catch the most specific exception you expect.


Basic Try / Except

Catches any error and continues running.

try:
    number = int("abc")
    print(number)
except Exception:
    print("Something went wrong")

Catching Specific Exceptions

Much safer and more readable.

try:
    value = 10 / 0
except ZeroDivisionError:
    print("Cannot divide by zero!")

Multiple Except Blocks

Each block handles a different failure.

try:
    num = int(input("Enter a number: "))
except ValueError:
    print("That was not a number!")
except KeyboardInterrupt:
    print("User cancelled input.")

Accessing the Error Message

Use as err to see the actual exception text.

try:
    file = open("missing.txt")
except FileNotFoundError as err:
    print("Error:", err)

Try / Except / Else

else runs only if no exception occurs.

try:
    result = 5 / 1
except ZeroDivisionError:
    print("Error!")
else:
    print("Success! Result is", result)

Try / Except / Finally

finally always runs, even if an exception happens. Great for closing files, database connections, etc.

try:
    f = open("data.txt")
    print(f.read())
except FileNotFoundError:
    print("File not found")
finally:
    print("Cleaning up...")

Combining all blocks

try:
    x = int("10")
except ValueError:
    print("Not a number")
else:
    print("Converted successfully!")
finally:
    print("Done")

Common Use Case: Safe User Input

while True:
    try:
        age = int(input("Enter age: "))
        break
    except ValueError:
        print("Please enter a valid number.")