CodingNic

Error Handling and Debugging

Finally

Error Handling and Debugging 22 min read

Finally

Finally

Sometimes you need code to run no matter what happens.

For example:

  • Close a file
  • Show a final message
  • Clean up resources
  • End a task safely

Python gives us finally for this.

What Is finally?

finally is a block that always runs.

It runs:

  • if the code succeeds
  • if an error happens

Basic Structure

python
try:
    # risky code
except:
    # handle error
finally:
    # always runs

Example: Final Message

python
try:
    print("Start")
except:
    print("Error")
finally:
    print("Done")

Output

text
Start
Done

Example: Bad Input

python
try:
    number = int(input("Enter number: "))
    print(number)
except:
    print("Invalid input")
finally:
    print("Program ended")

Output Example

text
Enter number: hello
Invalid input
Program ended

Example: File Cleanup

python
file = None

try:
    file = open("notes.txt")
    print(file.read())

except:
    print("File error")

finally:
    if file:
        file.close()
    print("Finished")

Why Use finally?

Use it when something must happen at the end.

Examples:

  • Close files
  • Disconnect tools
  • Save logs
  • Final message

finally with No Error

python
try:
    print(10 / 2)
except:
    print("Error")
finally:
    print("Always runs")

Output

text
5.0
Always runs

Code Along

Build a safe greeter.

Steps:

  • Ask for name
  • Print greeting
  • Always print Goodbye

Mini Challenge

Build a safe divider.

Steps:

  • Ask for two numbers
  • Divide them
  • Handle errors
  • Always print:
text
Done

Expected output:

text
Enter first number: 5
Enter second number: 0
Error
Done

Real World Use Case

Programs use finally for cleanup, closing files, ending sessions, and final system actions.

Quiz

  1. When does finally run?
  2. Does it run after an error?
  3. Why is finally useful?
  4. Name one real use of finally.

Assignment

Create a program that asks for a number and prints it. Handle bad input and always print Finished.

Summary

You learned that finally always runs and is useful for cleanup and final actions.