【问题标题】:JAVA - continue after file not found exceptionJAVA - 找不到文件异常后继续
【发布时间】:2014-11-22 10:35:46
【问题描述】:

我有以下从文件中读取数据的函数。 如果我得到一个 IO 异常,我想完成这个函数的运行并继续这个程序中的下一个函数。

我应该在代码中添加什么?

我尝试将 continue 添加到 finnally 块,但出现错误“continue 不能在循环外使用”。

public void readFromFile() throws Exception
{
    BufferedReader f= new BufferedReader(new FileReader("C:\\T.DAT"));
    String l="";

    try{
        do{
            l = f.readLine();
            if(l != null)
            {
                Car a = new Car();
                a.setFromLine(l);
                alCars.add(a);
            }
        } while(line !=null);
    }
    catch (Exception e)
    {
        System.out.println("can't open file IO ERROR. program is continueing");
    }
    finally
    { 
        f.close();
    }
}

【问题讨论】:

    标签: java exception bufferedreader filereader filenotfoundexception


    【解决方案1】:

    只需将 return; 放在 finally 块中

    【讨论】:

      【解决方案2】:

      您不能在循环外使用 continue。 Catch and finally 在循环之外。

      do while 子句中插入 try - catch - finally 即可。

      如果您使用 catch 块,则不必在方法签名后使用 throws。

      只需在 catch 块中捕获异常,然后在 finally 中做一些事情。 首先捕获 IOException,然后在所有其他情况下再次捕获异常。

      try { 
      //
      }
      catch ( IOException e ) {
      System.out.println("IO Exception occured");
      }
      catch ( Exception e ) {
      //other exceptions
      }
      finally { 
      //deinitialize
      }
      

      我不确定是否发生 ioexception,那么最后你必须关闭文件。也许它是空对象

      【讨论】:

        【解决方案3】:

        你不需要做任何事情。代码会在 finally 块执行后从函数中返回。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2018-07-06
          • 1970-01-01
          • 2021-06-20
          • 2013-08-02
          相关资源
          最近更新 更多