有没有简单的方法可以在java中用消息抛出异常? 在下面的方法中,我检查类型,如果类型不存在,我想抛出消息 不支持该类型,最简单的方法是什么?
public static SwitchType<?> switchInput(final String typeName) {
if (typeName.equals("java.lang.String")) {
}
else if (typeName.equals("Binary")) {
}
else if (typeName.equals("Decimal")) {
}
return null;
}
使用 Exception 构造函数,它接受一个字符串作为参数:
if (typeName.equals("java.lang.String")) {
}
else if (typeName.equals("Binary")) {
}
else if (typeName.equals("Decimal")) {
}
else {
throw new IllegalArgumentException("Wrong type passed");
}
处理非法参数的标准方法是抛出 an
IllegalArgumentException
:
} else {
throw new IllegalArgumentException("This type is not supported: " + typeName);
}
并尝试不返回 null(如果可以避免的话)。
这个方法真的不能抛出异常
因为函数输入参数中的
typeName
已经是String
了..
您可以使用 JProblem 来制作一条不错的消息
throw DefaultProblemBuilder.newBuilder()
.what("Wrong type passed")
.addSolution("Use java.lang.String, Binary or Decimal")
.buildAsException(IllegalArgumentException::new);