CodingNic

Files, Errors, and Automation

Try, Except, Else, Finally

Files, Errors, and Automation 26 min read

Try, Except, Else, Finally

Try, Except, Else, Finally

In the last lesson, you learned try and except.

Python also gives two more useful parts:

  • else
  • finally

These help you control what happens after success or error.

Review

python
try:
    # risky code
except:
    # run if error happens

What Does else Do?

else runs only if no error happens.

python
try:
    number = int("5")
except:
    print("Error")
else:
    print("Success")

Output

text
Success

What Does finally Do?

finally always runs.

It runs:

  • after success
  • after error
python
try:
    print("Start")
except:
    print("Error")
finally:
    print("Done")

Output

text
Start
Done

Full Example

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

Example Output (Good Input)

text
Enter number: 7
You entered 7
Program ended

Example Output (Bad Input)

text
Enter number: hello
Invalid input
Program ended

Why Use else?

It keeps success code separate from error code.

Cleaner code.

Why Use finally?

Useful for:

  • Closing files
  • Cleaning up resources
  • Final messages
  • Ending tasks safely

File Example

python
try:
    file = open("notes.txt")
    text = file.read()
except:
    print("File error")
else:
    print(text)
finally:
    print("Finished")

Output

text
Finished

(If the file is missing, you still see the final message.)

Code Along

Build a safe divider.

Steps:

  • Ask for two numbers
  • Divide them
  • Show error if needed
  • Always print Done

Mini Challenge

Build a safe login checker.

Steps:

  • Ask for age
  • Convert to number
  • If valid, print age
  • If invalid, print error
  • Always print Goodbye

Expected output:

text
Enter age: hello
Invalid input
Goodbye

Real World Use Case

Programs use finally for cleanup and else for successful actions after risky tasks.

Quiz

  1. When does else run?
  2. When does finally run?
  3. Why is finally useful?
  4. What is the benefit of else?

Assignment

Create a safe calculator that subtracts two numbers using try, except, else, and finally.

Summary

You learned how else runs after success and finally always runs after try and except.