CodeBlanks Logo Icon CodeBlanks

else and finally

Learn else and finally blocks.

else and finally

The else block runs only when try does NOT raise an error. The finally block always runs — error or not:

try:
    x = 10 / 2
except ZeroDivisionError:
    print("sıfıra bölme")
else:
    print(x)       # 5.0
finally:
    print("bitti")  # always

else runs code when try succeeds. finally is used for cleanup (closing files, releasing resources).

Both are optional, but finally is the safest block.

Difference between else and finally

else runs only if try succeeds — it is skipped on error. finally runs whether or not an error occurs:

# no error: else + finally
# error: except + finally (else is SKIPPED)

Put success-dependent code in else (e.g. printing the result). Put code that must always run in finally (e.g. closing a file).

This separation cleanly distinguishes cleanup from success code.

Practice try/else/finally together

Inside a try block write result = 10 / 2. Inside an except ZeroDivisionError: block write print("hata"). Inside an else: block write print(result). Inside a finally: block write print("bitti").

Starter code

main.py
# write try/except/else/finally
# successful division and cleanup

Sample solution

main.py
try:
    result = 10 / 2
except ZeroDivisionError:
    print("hata")
else:
    print(result)
finally:
    print("bitti")

Expected output

5.0
bitti

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Complete the finally keyword

Question
try:
    x = 10 / 2
____:
    print("bitti")
Answer
try:
    x = 10 / 2
finally:
    print("bitti")

Explanation: The finally block always runs.

2 Match else/finally

Term Meaning
else Runs if no error
finally Always runs
except Runs on error
try Protected code

3 When does the else block run?

  • Always
  • Only on error
  • Only when no error Correct answer
  • Never

Explanation: else runs only when the try block does not raise an error.

All lessons in Beginner