I'm relatively new with Java and I've always had problems with the Try/Catch functions in the code so I was wondering if you guys could help me out.
The issue I'm having is that I've written a try/catch but I get an error message saying that the exception is never thrown. I've written a similar statement in another part of my overall code that does work fine so I wonder what the issue is with this one then.
Here is the code:
public String getMatchedLogs(String matchStr, File logFile) {
String fileLine = "";
try {
Scanner ipScan = new Scanner(fileLine);
if (fileLine.indexOf(matchStr) > -1) {
output += fileLine;
}else{
System.out.println(fileLine.indexOf(""));
}
} catch (FileNotFoundException fnfe) {
System.out.println(fnfe.getMessage());
}
return fileLine;
} //end getMatchedLogs
The error is in the catch where it says the exception is never thrown. So if you guys could give me some insight on what's going on I'd greatly appreciate it.
You're not actually doing anything with the parameter File logFile
, you're only using the empty String fileLine = "";
you defined. Thus there's no file access going on, thus there's no chance of a FileNotFoundException
.
Get in the habit of looking up methods to see if they do what you think they do.
The Scanner constructor for File objects opens a file and declares that it can throw FileNotFoundException http://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html#Scanner(java.io.File)
The Scanner constructor for a String scans the string itself and does not open a file, so it won't need to throw the exception http://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html#Scanner(java.lang.String)
By the way: Your code seems to be using the scanner to write to the String passed in ("filine"). Strings are immutable in Java, and can't change when passed into a method.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With