'Haven't handled the FileNotFoundException file in Java program? [duplicate]
I have some trouble finding the file in a java program in mac system.
import java.io.File;
import java.util.Scanner;
import java.net.MalformedURLException;
import java.net.URL;
public class Data{
public static void main(String[] args){
File file = new File("/Users/project/test.txt");
Scanner sc = new Scanner(file);
while(sc.hasNextLine()){
System.out.println(sc.nextLine());
}
}
}
In the same directory, when I typed this command Javac Data.java, it would give this error
I have read multiple similar posts on StackOverflow, but unfortunately, I couldn't find a solution.
Data.java:9: error: unreported exception FileNotFoundException; must be caught or declared to be thrown Scanner sc = new Scanner(file);
^
1 error
I have tried setting the file path like:
"./test.txt"
"test.txt"
"/text.txt"
But still, the same error would occur.
I don't know if this is relevant, but I can only run the java command in the terminal in the ~ directory, and all the above java files are in the ~ directory too.
Does anyone have any suggestions?
Solution 1:[1]
Your code is not throwing an exception. Your error message does not mean that the FileNotFoundException is thrown.
You have a compile time error.
Whenever you open a file, it must be like this:
try {
File file = new File("/Users/tianrongzhen/project/test.txt");
} catch (Exception e) {
// handle exception here
}
Or like this:
public static void main(String[] args) throws FileNotFoundException {
File file = new File("/Users/tianrongzhen/project/test.txt");
// rest of your code
}
There are 2 kinds of exceptions: Checked and Unchecked.
A Checked exception can be considered one that is found by the compiler, and the compiler knows that it has a chance to occur, so you need to catch or throw it.
For example, opening a file. It has a chance to fail, and the compiler knows this, so you're forced to catch or throw the possible IOException or FileNotFoundException.
There is a huge difference between the two ways to handle exceptions above.
First one catches and handles Exception internally, so the caller doesn't have to do any exception handling.
Second one throws Exception, so the caller needs to handle the Exception.
Based on the question you have asked here, I would recommend you to read up on the basics on exception handling. Here is one resource, but feel free to explore.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
