Reputation: 31
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...
Upvotes: 0
Views: 1762
Reputation: 31417
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/finally
Option 1
try{
Scanner scan = new Scanner(new File(folder + "file.txt"));
data=scan.nextLine();
scan.close();
}
catch (FileNotFoundException ex)
{
System.out.println("Caught " + ex);
}
Option 2
try{
Scanner scan = new Scanner(new File(folder + "file.txt"));
data=scan.nextLine();
scan.close();
}
finally
{
System.out.println("Finally ");
}
Option 3
try{
Scanner scan = new Scanner(new File(folder + "file.txt"));
data=scan.nextLine();
scan.close();
}catch(FileNotFoundException ex){
System.out.println("Caught " + ex );
}finally{
System.out.println("Finally ");
}
Method 2: Throw exception using throw
and list all the exception with throws
clause.
class ThrowsDemo {
static void throwOne() throws IllegalAccessException {
System.out.println("Inside throwOne.");
throw new IllegalAccessException("demo");
}
public static void main(String args[]) {
try {
throwOne();
} catch (IllegalAccessException e) {
System.out.println("Caught " + e);
}
}
}
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.
Upvotes: 5
Reputation: 31196
how about
catch (FileNotFoundException ex)
{
// create a log entry about ex
}
Upvotes: 1
Reputation: 66657
FileNotFoundException
is checked exception, Due to catch or specify behavior, you need to either catch (or) specify it in throws clause of method declaration.
Upvotes: 2