Can I avoid catch block in Java?

时光毁灭记忆、已成空白 提交于 2019-12-11 20:18:59

问题


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...


回答1:


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.




回答2:


FileNotFoundException is checked exception, Due to catch or specify behavior, you need to either catch (or) specify it in throws clause of method declaration.




回答3:


how about

   catch (FileNotFoundException ex)
   {
       // create a log entry about ex
   }


来源:https://stackoverflow.com/questions/13882232/can-i-avoid-catch-block-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!