Task: Python Exception Handling FileNotFoundError – This Python programming tutorial covers an code example of the Python Exception Handling. If the FileNotFoundError exception occurs, this Python program will handle it gracefully by showing a simple and easy to understand error message.
The Source Code – Python Read and Show File Program with Exception Handling
If we try to open a file for reading which does not exist
Then a FileNotFoundError exception occurs and we will display our user defined custom error message. We have also imported the sys module. This is beacause we will use sys.exit() function to terminate the Python program if exception occurs after displaying a suitable messae to the user.
The output if FileNotFoundError ocurs
Sorry file not found
You may also like to read:
Python File Programs – Python File Handling
Write a Python file program read numbers write squares.
Python Text File Read and Show Contents Program
Python Text File Read and Display file data with Exception Handling FileNotFoundError
Python File Program Count Characters in Text File
Python Text File Program To Count Vowels