按类抓住异常? [英] Catch exception by class?

查看:161
本文介绍了按类抓住异常?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想抓住我期望的例外,但允许其他人通过。

I would like to catch an exception I expect but allow the others through.

我现在遇到的解决方案是:

The solution I have come to at the moment is:

protected void perfromCall(Class expectedException) throws Exception {
    try {
        response = call.call(request);
    } catch (Exception e) {
        if (!expectedException.isInstance(e)) {
            throw new Exception(e);
        }
    }
}

虽然这会默默地吃掉预期的异常,因为我想要抛出其他的,我不喜欢它是它包装意外的异常,现在我必须在调用者中捕获意外而不是之前(在尝试静默捕获预期的异常之前)我可以让它们冒泡到测试框架以使测试失败。

While this will silently eat the expected exception as I would like and throw the others, what I don't like about it is that it wraps the unexpected exceptions and now I have to catch unexpected in the caller whereas previously (before trying to silently catch expected exceptions) I could let them bubble up to the test framework to fail the test.

是否有一种更清晰的方式来说我期望A类的异常,但对于任何其他异常,请让它被链条抛出,直到上面的测试框架处理?

Is there a cleaner way to say "I expected exceptions of class A, but for any other exception, let it be thrown up the chain until it's handled by the test framework above"?

编辑:我想提供一些理由来说明为什么我要这样做,因为有一些答案(现已删除)质疑默默地吃异常。这适用于调用服务的测试框架。某些测试将错误的参数传递给服务,因此他们期望服务因捕获无效请求而抛出异常。因此,我想默默地吃掉预期的异常,但仍然让意外的异常冒泡并且测试失败。

I wanted to provide some justification as to why I want to do this as there were some answers (now deleted) that questioned silently eating an exception. This is for a test framework that calls a service. Some of the tests pass bad arguments to the service, so they expect an exception thrown by the service due to catching the invalid request. I therefore want to silently eat the expected exception, but still let unexpected exceptions to bubble up and fail the test.

推荐答案

protected void perfromCall(Class<?> expectedException) throws Exception {
    try {
        response = call.call(request);
    } catch (Exception e) {
        if (!expectedException.isInstance(e)) {
            throw e;
        }
    }
}

这篇关于按类抓住异常?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆