【问题标题】:java how to catch an exception in main? [closed]java如何在main中捕获异常? [关闭]
【发布时间】:2014-07-15 05:17:39
【问题描述】:

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

    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 中捕获所有异常, 所以这个类只接受一个字符串参数?

【问题讨论】:

  • catch(Exception) 怎么样?

标签: java exception try-catch main


【解决方案1】:

您的 readFileLines 方法缺少 throws 子句。

public String[] readFileLines() throws IOException {

【讨论】:

    猜你喜欢
    • 2012-12-22
    • 2010-10-28
    • 2023-03-14
    • 1970-01-01
    • 1970-01-01
    • 2017-09-09
    • 1970-01-01
    • 2011-02-12
    • 2023-03-12
    相关资源
    最近更新 更多