【问题标题】:JAVA: Why does my return error during compile?JAVA:为什么我在编译过程中返回错误?
【发布时间】:2013-02-04 09:28:03
【问题描述】:

我继承了一些编译时出错的代码。我得到以下两个错误之一:一个是 return 语句丢失,另一个是 throw/try/catch 不匹配。这个错误似乎return 语句的位置有关,我整个上午都在移动。它的当前位置产生error: missing return statement。被注释掉的任何一个返回都会产生一条消息,我必须用我的throw 声明trycatch

考虑:

static private List<File> getFileListingNoSort(File aDirectory) throws FileNotFoundException {

try {
    List<File> result = new ArrayList<File>();
    File[] filesAndDirs = aDirectory.listFiles();
    List<File> filesDirs = Arrays.asList(filesAndDirs);
    for(File file : filesDirs) {
         result.add(file); //always add, even if directory
         if ( ! file.isFile() ) {
              List<File> deeperList = getFileListingNoSort(file);
              result.addAll(deeperList);
           // return result;
         } //close if
      // return result;
     } // close for
     } // close try for getFileListingNoSort
   // return result;
 catch (Exception exp) {
      System.err.println("Error: " + exp.getMessage());
 } //close catch getFileListingNoSort
 return result;
} //close method

我会认为返回会在尝试之后,但在捕获之前。但是,这对我不起作用。我不太确定为什么我会得到这些区域,除了对程序如何与try/catch 一起流动的误解。谁能告诉我最适合退货的地方并解释原因?

【问题讨论】:

    标签: java return try-catch


    【解决方案1】:

    代替

    try {
        List<File> result = new ArrayList<File>();
    

    List<File> result = new ArrayList<File>();
    try {
    

    这样result 变量在try/catch 块之后不会超出范围。

    列表将包含添加到异常发生之前的所有元素。

    【讨论】:

      【解决方案2】:

      您在 try 块内定义 result,但(试图)在块外返回它。这将不起作用,因为该变量超出了范围。解决此问题的最简单方法是在 try 块之外声明结果变量。

      【讨论】:

        【解决方案3】:

        result 在 try 块中,它可能未初始化。将它放在 try 块之外将解决您的问题。

        【讨论】:

          【解决方案4】:

          首先,您尝试访问在try 块中声明的result 变量,并且不会在其中可见。

          【讨论】:

            【解决方案5】:

            您的方法必须始终返回,要么正常返回,要么发出异常。

            如果您的 catch 子句没有抛出 Exception,您需要一个 return 语句作为 catch 的最后一个语句,或者在 catch 之后。

            当你想在你的 try 块之外返回一些东西时,它的值必须在你进入 try 之前 被定义。

            例如,如果您想在 try 中返回一些值(以防万一),如果遇到异常则返回 null,您的代码将如下所示:

            try{
               ... do loads of stuff
               return value;
            } catch(Exception e) {
                e.printStackTrace(); //log it, whatever
                return null;
            }
            

            【讨论】:

              猜你喜欢
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 2021-04-28
              • 1970-01-01
              • 2016-07-31
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              相关资源
              最近更新 更多