java如何在main中捕获异常?

时间:2014-05-26 12:18:18

标签: java exception try-catch main

我需要从输入路径(文件)中读取行。 为此,main调用一个使用BufferedReader的类,它遍历每一行并将其添加到Array。 问题是: 我想要捕获主要类中的方法抛出的所有异常。

    public static void main (String[] args){
    if (args.length != 2){
        System.err.print("ERROR");
        return;
    }
    MyFileScript.sourceDir = args[SOURCE_DIR_INDEX];
    MyFileScript.commandFile = args[COMMAND_INDEX];
    try (FileReader file = new FileReader(MyFileScript.commandFile);
            BufferedReader reader = new BufferedReader(file)){

        fileParsing = new CommandFileParser(reader);
        sectionList = fileParsing.parseFile();

    }catch (FileNotFoundException error){
        System.err.print(ERROR_MESSAGE);
        return;
    }catch(IOException error){
        System.err.print(ERROR_MESSAGE);
        return;
    }catch(ErrorException error){
        System.err.print(error.getMessage());
        return;
    }
}


public class CommandFileParser {

public CommandFileParser (BufferedReader reader){
    this.reader = reader;
}

/**
 * read all lines from a file.
 * 
 * @return a string array containing all file lines
 */
public String[] readFileLines(){

    ArrayList<String> fileLines = new ArrayList<String>();

    String textLine;
    while ((textLine = this.reader.readLine()) != null){
        fileLines.add(textLine);
    }
    String[] allFileLines = new String[fileLines.size()];
    fileLines.toArray(allFileLines);
    return allFileLines;
}

在while循环中,我得到一个编译错误,用于解除IOException。

如何捕获main中的所有异常, 所以该类只接受一个字符串参数?

1 个答案:

答案 0 :(得分:1)

你的readFileLines方法缺少一个抛出条款。

public String[] readFileLines() throws IOException {