Java Program: File reading method with exception handling
3. Throw Exception if File Not Found
Write a Java program to create a method that reads a file and throws an exception if the file is not found.
Sample Solution:
Java Code:
Sample Output:
Error: test1.txt (The system cannot find the file specified)
Explanation:
In the above exercise,
- In this program, we have a method called readFile that takes a fileName parameter. To read the contents of the file, it creates a Scanner object using the File class.
- In the main method, we call the readFile method and provide the name of the file we want to read. If the file is not found, a FileNotFoundException is thrown.
- In the readFile method, we declare a File object and initialize it with the given fileName. We then create a Scanner object using the file. If the file is not found, a FileNotFoundException is thrown.
- A try-catch block is used in the main method to catch the FileNotFoundException and print an error message.
Flowchart:
For more Practice: Solve these Related Problems:
- Write a Java program to attempt to read a file from a given path and throw a FileNotFoundException if it does not exist, then handle it gracefully.
- Write a Java program to throw a custom ConfigurationFileNotFoundException when a required configuration file is missing.
- Write a Java program to check the file extension of an input file and throw an exception if it is not ".txt".
- Write a Java program to open a file for reading and throw an exception if the file cannot be accessed due to insufficient permissions.
Go to:
PREV : Throw Exception for Odd Number.
NEXT : Throw Exception for Positive Numbers in File.
Java Code Editor:
Improve this sample solution and post your code through Disqus
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.