← Back to Blog

There's more to error handling than catching

The problem...

You know try / except. You catch the error. You handle it. Done.

But sometimes you need more. Code that runs only when everything worked. Code that runs no matter what — success or failure.

try / except alone can't do that cleanly.

The idea!

Two more blocks complete the picture. else runs when the try succeeded — no errors. finally runs always — whether the try succeeded or failed.

The full syntax

try:
    # code that might fail
except ErrorType:
    # runs if try failed
else:
    # runs if try succeeded — no errors
finally:
    # always runs — success or failure

else — when everything worked

try:
    age = int(input("Enter your age: "))
except ValueError:
    print("Numbers only, please.")
else:
    print(f"Your age is {age}.")    # only runs if no error

If int() succeeds — else runs. If it fails — except runs, else is skipped. Cleaner than putting the success code inside try.

finally — always runs

try:
    age = int(input("Enter your age: "))
except ValueError:
    print("Numbers only, please.")
finally:
    print("Thank you for using this program.")

Valid input or not — finally always executes. Use it for cleanup code that must run regardless.

All four together

def get_age():
    try:
        age = int(input("Enter your age: "))
    except ValueError:
        print("Numbers only, please.")
        return None
    else:
        print(f"Valid age received: {age}.")
        return age
    finally:
        print("Input attempt complete.")

result = get_age()
print(result)
# Valid input:
# Enter your age: 25
# Valid age received: 25.
# Input attempt complete.
# 25

# Invalid input:
# Enter your age: abc
# Numbers only, please.
# Input attempt complete.
# None

finally runs in both cases. else only runs when there's no error.

Heads up!

  • else — runs only when try succeeded, skipped if except ran
  • finally — always runs, no exceptions
  • You don't need all four — use only what you need
  • finally runs even if there's a return inside try or except

The mindset shift

Stop thinking: "I just need to catch the error."

Start thinking: "What runs on success? What always runs? Plan for both."

What you should understand now

  • else — runs when try succeeds, skipped when except runs
  • finally — always runs, regardless of success or failure
  • Use else for success logic — use finally for cleanup
  • You don't need all four blocks — use only what the situation requires
[ login to bookmark ] // copied! 20 views · 2 min
// resources
Code Example try_except_else_finally.py
← prev Don't let errors crash your program next → Throw your own errors
// 0 comments
// No comments yet. Be the first.
// leave a comment

// Your comment will appear after approval.