gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 06:54:49 25 4
gpt4 key购买 nike

我正在构建一个自定义异常,如果数组不包含 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);
}
}
}

自定义异常.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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com