有
一个简单的方法可以在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;
}
使用将
字符串作为参数的异常构造函数:
if (typeName.equals("java.lang.String")) {
}
else if (typeName.equals("Binary")) {
}
else if (typeName.equals("Decimal")) {
}
else {
throw new IllegalArgumentException("Wrong type passed");
}
处理非法参数的标准方法是抛出一个IllegalArgumentException
:
} else {
throw new IllegalArgumentException("This type is not supported: " + typeName);
}
如果可以避免,尽量不要返回 null。
此方法实际上
无法引发异常因为函数输入参数中的typeName
已经是一个String
。