Handling FileNotFoundError Exception in Python File Handling Program
3. Handle FileNotFoundError Exception When Opening a File
Write a Python program that opens a file and handles a FileNotFoundError exception if the file does not exist.
exception FileNotFoundError:
Raised when a file or directory is requested but doesn’t exist. Corresponds to errno ENOENT.
Sample Solution:
Code:
Explanation:
In the above exercise, the "open_file()" function takes a "filename" parameter representing the name of the file to be opened. Inside the function, we attempt to open the file using the open function with mode 'r' to read the file.
If the file exists and can be opened successfully, we read the contents and print them. Finally, we close the file.
However, if a FileNotFoundError exception occurs because the file does not exist, the program jumps to the except block. In the except block, we handle the exception by printing an error message indicating that the file was not found.
Output:
Input a file name: test.txt Error: File not found.
Input a file name: file2.txt File contents: Raised when an operation or function receives an argument that has the right type but an inappropriate value, and the situation is not described by a more precise exception such as IndexError.
Flowchart:

For more Practice: Solve these Related Problems:
- Write a Python program that attempts to open a non-existent file in read mode and catches the FileNotFoundError to display a user-friendly message.
- Write a Python program to implement a function that checks if a file exists before opening it, raising and handling FileNotFoundError if not found.
- Write a Python program that uses try-except to open a file and logs the error message when the file is not found.
- Write a Python program to use the os.path module to check file existence and handle exceptions accordingly when opening a file.
Go to:
Previous: Handling ValueError Exception in Python integer input program.
Next: Handling TypeError Exception in Python numeric input program.
Python Code Editor:
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.