一次抛出多个相同类型的异常

Throwing multiple exceptions of the same type at once

我的意图是一次抛出两个 Exception。代码:

    String str = "foo";

    if (str.length() < 5) {
        throw new Exception("At least 5 characters."); // exception 1
    }

    if (!str.matches(".*[0-9]+.*")) {
        throw new Exception("At least 1 digit."); // exception 2
    }

foo 长度少于 5 个字符且不包含任何数字。但是当我运行这个程序时,只抛出exception 1

如何抛出多个异常(相同类型)?还是我的方法被误导了,我应该换一种方式吗?

那是不可能的。而是测试您想要的条件。喜欢,

String str = "foo";
boolean len = str.length() < 5;
boolean digit = !str.matches(".*[0-9]+.*");
if (len && digit) {
    throw new Exception("At least 5 characters and 1 digit."); // both 1 and 2
} else if (len) {
    throw new Exception("At least 5 characters."); // exception 1
} else if (digit) {
    throw new Exception("At least 1 digit."); // exception 2
}

您一次不能抛出多个异常,因为它们会中断执行。您可以单独测试每个可能的问题,并在末尾抛出一个异常,其中包含以易于解析的方式分隔的每个失败的测试(此处可能最好使用逗号)。

如果您正在检查可能存在的问题列表,并且需要报告 所有 个问题,那么这样做可能更简洁:

String str = "foo";

List<String> errors = new ArrayList<>();

if (str.length() < 5) {
    errors.add("At least 5 characters."); // exception 1
}

if (!str.matches(".*[0-9]+.*")) {
    errors.add("At least 1 digit."); // exception 2
}

// Check for more stuff

if (!errors.isEmpty()) {
    throw new Exception("There are problem(s) found:\n" + String.join("\n", errors));
}

实际上,这与其他 answers/comments 提出的方法相同,但对于更复杂的场景,这种方法有点 cleaner/neater。