Inside a method, I use a Scanner to read text inside a file. This file doesn’t always exist, and if it doesn’t, I want simply to do nothing (i.e. no scan).
Of course I could use a try/catch like this:
String data = null;
try
{
Scanner scan = new Scanner(new File(folder + "file.txt"));
data=scan.nextLine();
scan.close();
}
catch (FileNotFoundException ex)
{
}
My question is what can I do to avoid the try/catch? Because I don’t like local variable unused. I was thinking of something like:
String data = null;
File file_txt = new File(folder + "file.txt");
if (file_txt.exists())
{
Scanner scan = new Scanner(file_txt);
data=scan.nextLine();
scan.close();
}
But of course with this I get an error in Netbeans and I can’t build my project…
No, It’s checked exception. try must be followed with either catch block and/or finally block. There are two method for handling checked exception.
Method 1 : Either wrap your code using
try/catch/finallyOption 1
Option 2
Option 3
Method 2: Throw exception using
throwand list all the exception withthrowsclause.Note : Checked Exception means Compiler force you to write something to handle this error/exception. So, AFAIK, there is no any alternative for checked exception handling except above method.