Account
Categories

Else and Finally Block


The else block executes when the try block executes successfully without any exception; otherwise, it skips the code.

The finally block always executes, regardless of errors occurring.

Now you can clearly understand how else and finally block with the help of this flowchart.

Start
  |
  v
Write code in the Try block
  |
  v
Run Try block
  |
  v
Is there any error?
   /      \
 Yes        No
  |          |
  v          v
Run Except   Run Else block
 block        |
  |           v
  v        Try finishes
Handle error / Show error
  |
  v
Run the Finally block
  |
  v
End

Syntax

try:
    # risky code
except ExceptionType:
    # error handling code
else:
    # runs if no error in try
finally:
    # always runs

Example

try:
    num = 40
    result = num + 10
except Exception:
    print("Error")
else:
    print("Else block: Result =", result)
finally:
    print("Finally block: always executes")

Output

Exercise

Write a Python program using try, except, else and finally block. In try block divide 10 by 2 and print result.