Tuesday, August 26, 2025

🐍 "FINALLY AND ELSE" IN PYTHON ERROR HANDLING

In Python error handling, we have seen how try and except work together. But sometimes, we want to run extra code whether or not an error happens. This is where else and finally come in.

πŸ”Ή The else Block

The else block runs only if no error occurs in the try block.


try:
    number = int(input("Enter a number: "))
except ValueError:
    print("That's not a number!")
else:
    print("Great! You entered:", number)
    

πŸ‘‰ If the user enters 10, output will be:
Great! You entered: 10
πŸ‘‰ If the user enters hello, output will be:
That's not a number!

πŸ”Ή The finally Block

The finally block runs no matter what happens — whether an error occurs or not. It is often used for cleanup actions like closing files or releasing resources.


try:
    f = open("data.txt", "r")
    content = f.read()
except FileNotFoundError:
    print("File not found!")
finally:
    print("Closing file (if it was opened).")
    

πŸ‘‰ If data.txt exists, the file will be read and then closed.
πŸ‘‰ If data.txt does not exist, you still see:
File not found!
Closing file (if it was opened).

πŸ”Ή Syntax of try–except–else–finally


try:
    # Code that might raise an error
except SomeError:
    # Handle the error
else:
    # Runs if no error happens
finally:
    # Always runs (cleanup code)
    

⚠️ Common Mistakes

  • Using capitalized Else or Finally → must be lowercase.
  • Forgetting that finally runs always, even if there is an error.
  • Using finally without cleanup logic — defeats its main purpose.

πŸ–₯️ Practice in Browser

No comments:

Post a Comment

🐍What is scikitlearn??