java - 是否可以从 assert 方法引发自定义异常?

标签 java assert

我必须验证包含大约 40 个必填字段的请求。

我想通过避免经典的 if (field1 == null) throw new XXException("msg");

来做到这一点

例如我有以下代码:

if (caller == null)
{
    // Caller cannot be empty
    throw new CallerErrorException(new CallerError("", "incorrect caller"));
}
if (person == null)
{
    // Person cannot be empty
    throw new PersonErrorException(new CustomerError("", "incorrect customer"));
}
if (module == null)
{
    // Module cannot be empty
    throw new ModuleErrorException(new ModuleError("", "module must be X"));
}

如您所见,根据哪个字段为空,将抛出带有自定义消息的特定自定义异常。

所以,我想要这样的东西:

assertNotEquals(call, null, new CallerErrorException(new CallerError("", "incorrect caller")));
assertNotEquals(person, null, new PersonErrorException(new CustomerError("", "incorrect caller")));
assertNotEquals(module , null, new ModuleErrorException(new ModuleError("", "incorrect caller")));

是否有允许我执行此操作的内置功能?

我知道 assertEquals 会生成 assertionError,但我需要生成自定义异常。

最佳答案

没有内置的东西可以为此工作,但您当然可以编写自己的:

static void checkNull(Object val, Class exClass, Class innerClass, String arg1, String arg2)
    throws Exception {
    if (val != null) {
        return;
    }
    Object inner = innerClass
        .getDeclaredConstructor(String.class, String.class)
        .newInstance(arg1, arg2);
    throw (Exception)exClass
        .getDeclaredConstructor(innerClass) // This may need to be changed 
        .newInstance(inner);
}

以上代码根据需要使用反射构建异常对象。如果它需要内部错误对象的父类(super class)来匹配正确的类型,您可能必须更改传递给异常对象的构造函数的类型。

现在您可以编写如下代码:

checkNull(caller, CallerErrorException.class, CallerError.class, "", "incorrect caller");
checkNull(person, PersonErrorException.class, PersonError.class, "", "incorrect person");

这种方法可以让您避免在不需要抛出异常对象的情况下创建异常对象。

关于java - 是否可以从 assert 方法引发自定义异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24195979/

相关文章:

java - 使用assertj时是否可以记录被断言的字段的名称和值以及条件?

c# - 如何将 "Assert.That()"列表中的项目与 NUnit 匹配某些条件?

java - 当我启动我的 Tomcat 时,不是打开欢迎文件,而是下载它。有人可以帮我从这里出去吗。?

java - 获取文本节点内 anchor 中的文本

java - 更改事件监听器中的变量?

java - 如何使用按钮关闭 Java SWT 窗口?

objective-c - 在 swift assert(0) 中无法将 Int 类型的值转换为预期的参数类型 Bool

java - 找不到提供程序 ( ClassNotFoundException ) maven 项目

java - 如何断言每个 jUnit 的 HTML 有效

c++ - 什么时候应该使用 assert()?