开发者

Catch exception by class?

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.

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"?

Edit: 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;
        }
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜