java - 方法返回类型混淆

时间:2016-03-05 20:11:46

标签: java return

我试图从函数返回2D矩阵。 Eclipse抱怨函数的返回类型

import java.io.*;
import java.util.Arrays;
import java.util.List;
import com.opencsv.CSVReader;

public class myClass {

    private static String inFile = "myfile.csv";

    private String[][] readCsv() {
        File file1 = new File(inFile);
        if (file1.exists()) {
            System.out.println("File " + inFile + " exists. length : " + inFile.length());
        } else {
            System.out.println("File " + inFile + " does not exist!");
        }

        try {
            // Read all
            CSVReader csvReader = new CSVReader(new FileReader(new File(inFile)));
            List<String[]> list = csvReader.readAll();

            // Convert to 2D array
            String[][] dataArr = new String[list.size()][];
            dataArr = list.toArray(dataArr);

            return dataArr;
        } catch (Exception ex) {
            // Do something with mistake or ignore
            ex.printStackTrace();
        }
    }

    public static void main(String[] args) {
        myClass mc = new myClass();
        String[][] csvContents = mc.readCsv();

        for (int k = 0; k < 10; k++) {
            System.out.println(Arrays.toString(csvContents[k]));
        }
    }

}

eclipse告诉我的错误是This method must return a result of type String[][]。返回的值dataArr的类型为String[][]&amp;方法readCsv被指示返回String[][]

我无法弄清楚错误的位置。

4 个答案:

答案 0 :(得分:5)

如果try块抛出异常,你将不得不返回一些东西:

public String[][] myMethod() {
    String[][] arr = new String[1][];
    try {
        arr = methodThatCanThrowException(); // If this method throws an exception
        return arr;                          // this return will not execute
    } catch (Exception ignored) {}

    return arr;                              // Return something after the try/catch block
}

您如何处理这取决于您,您可以返回一些默认值或null

答案 1 :(得分:3)

该方法必须在每个可能的分支中返回String[][]。在这里,您只从try返回 - 如果它没有成功完成并抛出异常,catch将完成而不返回任何内容,从而导致错误。你可以在try-catch块之后return,就像@Marv建议的那样,但恕我直言,正确的Java方法只是允许异常被抛出方法而不是捕获它:

// should probably throw something more specific
private String[][] readCsv() throws Exception { 
    // Read all
    CSVReader csvReader = new CSVReader(new FileReader(new File(inFile)));
    List<String[]> list = csvReader.readAll();

    // Convert to 2D array
    String[][] dataArr = new String[list.size()][];
    dataArr = list.toArray(dataArr);

    return dataArr;
}

答案 2 :(得分:2)

如果在readCsv中发现异常,则不会返回任何内容。你需要在这里归还一些东西。

catch (Exception ex) {
        // Do something with mistake or ignore
        ex.printStackTrace();
        return SOMETHING;
    }

答案 3 :(得分:2)

当捕获到异常并且代码函数继续时,没有返回值