用消息抛出简单异常

问题描述 投票:0回答:4

有没有简单的方法可以在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;
}
java exception
4个回答
3
投票

使用 Exception 构造函数,它接受一个字符串作为参数:

        if (typeName.equals("java.lang.String")) {

        }
        else if (typeName.equals("Binary")) {

        }
        else if (typeName.equals("Decimal")) {

        }
        else {
           throw new IllegalArgumentException("Wrong type passed");
        }

2
投票

处理非法参数的标准方法是抛出 an

IllegalArgumentException
:

} else {
    throw new IllegalArgumentException("This type is not supported: " + typeName);
}

并尝试不返回 null(如果可以避免的话)。


0
投票

这个方法真的不能抛出异常
因为函数输入参数中的

typeName
已经是
String
了..


0
投票

您可以使用 JProblem 来制作一条不错的消息

throw DefaultProblemBuilder.newBuilder()
    .what("Wrong type passed")
    .addSolution("Use java.lang.String, Binary or Decimal")
    .buildAsException(IllegalArgumentException::new);
© www.soinside.com 2019 - 2024. All rights reserved.