Warmup

Write a function that takes an integer and returns its square.

Agenda

Lesson: Exception Handling with else and finally

We didn't cover else and finally in our lesson on exception-handling. This lesson serves to fill in that gap.

Review

  • Exceptions stop a program unless handled
  • We use try/except to catch them
  • We also learned how to raise exceptions
  • But Python has two more keywords: else and finally

The else Block

  • Runs only if no exception occurs
try:
    num = int(input("Enter a number: "))
    result = 10 / num
except ZeroDivisionError:
    print("You can’t divide by zero!")
except ValueError:
    print("That wasn’t a number!")
else:
    print("Division successful:", result)
  • Good place for code that should only run if everything worked

The finally Block

  • Always runs, no matter what
  • Useful for cleanup (closing files, releasing resources)
try:
    f = open("data.txt")
    data = f.read()
except FileNotFoundError:
    print("File not found!")
finally:
    print("Closing file...")
    f.close()

Example: Combining All

def safe_divide(a, b):
    try:
        result = a / b
    except ZeroDivisionError:
        return "Error: Division by zero"
    else:
        return f"Result is {result}"
    finally:
        print("Division attempt finished")

print(safe_divide(10, 2))
print(safe_divide(10, 0))

When to Use else

  • For code that should only run when no exceptions happen
  • Keeps try block shorter (only risky code inside)

When to Use finally

  • For tasks that must always happen
  • Examples:
    • Closing files
    • Releasing a lock
    • Printing a status message

Quick Check

  • When does else run in exception handling?
  • When does finally run?
  • Why is it good practice to keep only risky code inside the try block?

Practice Challenge

Write a function get_number() that:

  • Asks the user for input
  • Tries to convert it to an integer
  • If conversion fails, print "Error: not a number"
  • If successful, print "Success!"
  • Always print "Done" at the end (whether successful or not)