自定义异常字符串数组

时间:2016-03-14 10:13:20

标签: java arrays exception exception-handling

我正在构建一个自定义异常,如果一个数组不包含5个字符串,则基本上会抛出该异常。这就是我到目前为止所拥有的。真正重要的唯一例外是自定义的例外,因为我必须证明如果在分割输入文件后数组不包含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);
        }
    }
}

CustomException.java

package exceptions;

public class CustomException extends Exception {
    private int fieldcount;

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

    public int getCount() {
        return fieldcount;
    }
}

1 个答案:

答案 0 :(得分:4)

CustomException扩展Exception,以便在第一个捕获区中捕获任何CustomException

重新排列块,以便catch(CustomException e)块位于catch(Exception e)块之前