抛出nex异常返回阅读

时间:2011-12-14 13:17:37

标签: java exception

我必须阅读文本并创建了一个方法

public void load(String fname){

    try{

        BufferedReader reader = new BufferedReader(new FileReader(fname));

        String id_cliente = reader.readLine();
        while(id_cliente!=null){

            String name_surname = reader.readLine();
            int num_titoli = Integer.parseInt(reader.readLine());

            String[] sb = name_surname.split(" ");

            Cliente cl = new Cliente(id_cliente,sb[0],sb[1]);

            clientilist.put(Integer.parseInt(id_cliente.substring(1)),cl);

            for(int i = 0; i < num_titoli; i++){

                cl.addTitolo(String titolo = reader.readLine());
            }

            id_cliente = reader.readLine();
        }
    }
    catch(FileNotFoundException fnfe){

            try{


            }
            catch(FileNotFoundExeption fnfe){

                System.exit(0);
            }
    }
    catch(IOException ioe){

    }
}

我要做的是检查fname文件是否存在。如果不是FileNotFoundException将被抛出。我必须尝试打开另一个文件。如果它不存在那么退出并显示错误消息。我可以吗?

2 个答案:

答案 0 :(得分:1)

在第一个try catch语句的catch块中,您可以放置​​所需的任何代码,并在发生异常时执行。您可以读取另一个文件,尝试再次读取同一文件,要求用户指向正确的文件,...

但如上所述,更好的解决方案是在创建阅读器之前检查文件是否存在。如果失败了你可以回退到另一个文件(如果那个也失败了怎么办?)

在下一个代码中,我调整了您的方法以检查并在文件无效时抛出异常。在使用该方法时,您可以对此做出反应。请注意,如果您提供了2个无效的文件名,则尚未打开任何读者。

try{
   load(fname);
}catch(Exception e){
   try{
      load(alternativeFName);
   }catch(Exception e){
      System.out.println("None of the files are available");
      e.printStackTrace();
   }
}

这就是你的加载函数的样子:

public void load(String fname) throws Exception {
   // try opening file    
   File file = new File(fname);
   // check if valid file
   if( !file.exists() ){
      // if no valid file throw exception so we can react on that
      throw new Exception("File not available: "+fname);
   }
   //your code for reading here, at this point you know the file exists
   //...
}

答案 1 :(得分:0)

首先检查文件是否存在会更简单,而不是等待例外:

File f = new File(fname);
if (!f.exists()) {
    // similarly, check for the existence of the other file, exit if necessary
}