Task: Python Exception Handling FileNotFoundError – If the user enters a wrong name or path for the file, this program will handle it gracefully by showing a simple and easy to understand error message.
How To Handle FileNotFound Exception in Python?
We will use try-except block to handle FileNotFound exception.
Note that the try-block will have the code to be monitored for any exception. On the other hand the except-block will contain the code to handle the exception occured.
The Source Code – Python Read and Show File Program with Exception Handling
Python Exception Handling FileNotFoundError
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.
Sorry file not found
This is a very simple example of a File handling program showing the occurrence of an error and to handle it gracefully using the Python code.
Why To Handle FileNotFound Exception?
This program may be written without handling the exception, but in this case, the program will terminate and will show default error message. The default messages may be hard to read and understand.
Therefore, we use the exception handling in this program.
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