🚀 LEVEL UP TO SENIOR:Unlock 500+ Advanced Practical Challenges & Exercises.
🎓 COURSERA PARTNER:Earn professional Google, Meta, and IBM certificates to supercharge your resume.
REFERENCEpython

python Documentation

LOADING ENGINE...

else Block (Exceptions)

AI & DATA SCIENCE // else-block-exceptions

The else clause on a try statement runs only if the try block completed without raising any exception at all.

Syntax

try:
    risky_code()
except SomeError:
    handle_error()
else:
    only_runs_if_no_exception()

Deep Dive Course

Code placed in a try/except's else clause runs only after the try block finishes successfully, with no exception raised — if any exception occurred and was caught, the else block is skipped entirely. This lets you separate 'the code that might fail', in try, from 'the code that should only run on success', in else, which is clearer than just adding more code to the end of the try block, since that would also be caught by an except if it happened to raise the same exception type by coincidence.

1Understanding else Block (Exceptions)

Code placed in a try/except's else clause runs only after the try block finishes successfully, with no exception raised — if any exception occurred and was caught, the else block is skipped entirely. This lets you separate 'the code that might fail', in try, from 'the code that should only run on success', in else, which is clearer than just adding more code to the end of the try block, since that would also be caught by an except if it happened to raise the same exception type by coincidence.

💡

Putting success-only code in else instead of at the end of the try block avoids accidentally catching an exception from that success code as if it came from the risky operation you were actually trying to guard.

editor.html
try:
    number = int("42")
except ValueError:
    print("Not a valid number")
else:
    print(f"Parsed successfully: {number}")
localhost:3000

2Practical Example

Here is a real-world application of else Block (Exceptions) showing how it is used in production Python code.

editor.html
try:
    f = open("config.txt")
except FileNotFoundError:
    print("Config file missing, using defaults")
else:
    print("Config loaded")
    f.close()
localhost:3000

3Best Practices

Follow these guidelines when working with else Block (Exceptions):

1. Use an else clause for code that should run only on success, so it isn't accidentally covered by the try's except handlers

2. Keep the try block itself limited to just the operation that can fail, moving follow-up logic into else

3. Avoid overusing else here if it doesn't add clarity — sometimes just continuing after the try/except is simpler and equally correct

⚠️

Tip: Putting success-only code in else instead of at the end of the try block avoids accidentally catching an exception from that success code as if it came from the risky operation you were actually trying to guard.

editor.html
try:
    number = int("42")
except ValueError:
    print("Not a valid number")
else:
    print(f"Parsed successfully: {number}")
localhost:3000

Examples

Example 01Basic Usage
try:
    number = int("42")
except ValueError:
    print("Not a valid number")
else:
    print(f"Parsed successfully: {number}")
Example 02Advanced Example
try:
    f = open("config.txt")
except FileNotFoundError:
    print("Config file missing, using defaults")
else:
    print("Config loaded")
    f.close()

Best Practices

  • Use an else clause for code that should run only on success, so it isn't accidentally covered by the try's except handlers
  • Keep the try block itself limited to just the operation that can fail, moving follow-up logic into else
  • Avoid overusing else here if it doesn't add clarity — sometimes just continuing after the try/except is simpler and equally correct

Interview Question

Why would you put code in a try statement's else clause instead of just adding it at the end of the try block?

Hint: Think about what happens if that extra code itself raises the same kind of exception you're catching.

If you add follow-up code directly at the end of the try block and it happens to raise the same exception type your except clause is catching, it would be caught too, even though it's unrelated to the original risky operation you meant to guard, which can mask a real bug. Putting that follow-up code in else instead means it only runs after the try block has already succeeded, and any exception it raises is not caught by that except clause, since else is outside the try block's own exception-catching scope.

Exercises

MediumPractice using else Block (Exceptions) in a real scenario.
View Solution
try:
    number = int("42")
except ValueError:
    print("Not a valid number")
else:
    print(f"Parsed successfully: {number}")

Frequently Asked Questions

Why would you put code in a try statement's else clause instead of just adding it at the end of the try block?

If you add follow-up code directly at the end of the try block and it happens to raise the same exception type your except clause is catching, it would be caught too, even though it's unrelated to the original risky operation you meant to guard, which can mask a real bug. Putting that follow-up code in else instead means it only runs after the try block has already succeeded, and any exception it raises is not caught by that except clause, since else is outside the try block's own exception-catching scope.

Related Functions

try-blockexcept-blockfinally-block