Monday, April 21, 2025

Try, Except and Finally - Python Exception Handling

import os

try:
    os.remove('test-file.txt')
    print('File Deleted')
except:
    print('Script fails - there\'s no file there')
finally:
    os.system('ping google.com')

This Python code imports the "os" module using the "import" statement.

The code then enters a "try-except-finally" block. The "try" block attempts to delete a file named "test-file.txt" using the "os.remove()" function. If the file does not exist or the user does not have permission to delete the file, the "os.remove()" function will raise an error. If the file is successfully deleted, the message "File Deleted" is printed to the console screen using the "print()" function.

If the "try" block raises an exception, the "except" block is executed. In this case, the "except" block will print the message "Script fails - there's no file there" to the console screen using the "print()" function.

The "finally" block is always executed, regardless of whether the "try" or "except" blocks were executed. In this case, the "finally" block calls the "os.system()" function to execute the "ping google.com" command. This command pings the Google website to test the network connectivity.

So, when the program is executed, the code will first attempt to delete the "test-file.txt" file using the "os.remove()" function. If the file is successfully deleted, the message "File Deleted" is printed to the console screen. If the file does not exist or the user does not have permission to delete the file, the message "Script fails - there's no file there" is printed to the console screen.

Finally, regardless of whether the file was deleted or not, the "os.system()" function is called to execute the "ping google.com" command to test the network connectivity.

No comments:

Post a Comment

Tkinter Introduction - Top Widget, Method, Button

First, let's make shure that our tkinter module is working ok with simple  for loop that will spawn 5 instances of blank Tk window .  ...