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