java - 自定义异常字符串数组

标签 java arrays exception

我正在构建一个自定义异常,如果数组不包含 5 个字符串,则基本上会抛出该异常。这是我到目前为止所拥有的。唯一真正重要的异常(exception)是自定义异常(exception),因为我只需表明如果在分割输入文件后数组不包含 5 个字符串,则会引发该异常。任何帮助,将不胜感激。谢谢!

package exceptions;

import java.io.File;
import java.util.Scanner;

public class Exceptions {

    public static void main(String[] args) {
        String input, formattedInt, field[];
        int recordNumber = 0;
        int length;
        Scanner inputFile;

        try {
            inputFile = new Scanner(new File("data.txt"));
            while (inputFile.hasNextLine()) {
                recordNumber++;
                formattedInt = String.format("%2d", recordNumber);
                input = inputFile.nextLine();
                field = input.split(",");
                length = field.length;
                if (field.length != 5) throw new CustomException(field.length);
                System.out.println("Record #" + formattedInt + ": " + input);
            }
        } catch (Exception e) {
            System.out.println("Error! Problem opening file.\nError was: " + e);
        } catch (CustomException ce) {
            System.out.println(ce);
        }
    }
}

自定义异常.java

package exceptions;

public class CustomException extends Exception {
    private int fieldcount;

    public CustomException(int fieldCount) {
        super("Invalid Count: " + fieldCount);
    }

    public int getCount() {
        return fieldcount;
    }
}

最佳答案

CustomException 扩展了 Exception,因此任何 CustomException 都将在第一个 catch block 中捕获。

重新排列 block ,使 catch(CustomException e) block 位于 catch(Exception e) block 之前

关于java - 自定义异常字符串数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35984686/

相关文章:

c# - 为什么我的 WCF channel 失败?

python - 计算numpy数组中的相邻单元格

javascript - 需要按多选值数组进行分组

java - 如何让android中的imagebutton保持高亮显示?

java - 如何将文本设置到位于 jFrame 内的 jPanel 内的 jTextField 中以从其他 jFrame 中

javascript - 如何在 Javascript 中从数组中查找上一个或下一个元素?

exception - 如何在 Haskell 中抛出异常并退出程序?

java - 在基于 block 的步骤期间中止批处理作业

java - 将 CoreNLP 与 Jython 结合使用时出现 edu.stanford.nlp.util.ReflectionLoading$ReflectionLoadingException

java - 如何使用带参数的正则表达式匹配 Drools 中的字符串?