在Java中捕获通用异常? [英] Catch a generic exception in Java?

查看:333
本文介绍了在Java中捕获通用异常?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们在工作中使用JUnit 3,没有 ExpectedException 注释。我想在我们的代码中添加一个实用程序来包装:

We use JUnit 3 at work and there is no ExpectedException annotation. I wanted to add a utility to our code to wrap this:

 try {
     someCode();
     fail("some error message");
 } catch (SomeSpecificExceptionType ex) {
 }

所以我试过这个:

public static class ExpectedExceptionUtility {
  public static <T extends Exception> void checkForExpectedException(String message, ExpectedExceptionBlock<T> block) {
     try {
        block.exceptionThrowingCode();
        fail(message);
    } catch (T ex) {
    }
  }
}

但是,Java不能在catch块中使用泛型异常类型。

However, Java cannot use generic exception types in a catch block, I think.

如何处理Java限制?

How can I do something like this, working around the Java limitation?

有没有办法检查 ex 变量是否类型为 T

Is there a way to check that the ex variable is of type T?

推荐答案

您可以传递Class对象,并以编程方式检查。

You could pass the Class object in and check that programatically.

public static <T extends Exception> void checkForException(String message, 
        Class<T> exceptionType, ExpectedExceptionBlock<T> block) {
    try {
       block.exceptionThrowingCode();
   } catch (Exception ex) {
       if ( exceptionType.isInstance(ex) ) {
           return;
       } else {
          throw ex;  //optional?
       }
   }
   fail(message);
}

//...
checkForException("Expected an NPE", NullPointerException.class, //...

我不知道你是否想要重新抛出;推翻会同样失败/错误的测试,但语义上我不会,因为它基本上意味着我们没有得到我们预期的异常,所以代表一个编程错误,而不是测试环境错误。

I'm not sure if you'd want the rethrow or not; rethrowing would equally fail/error the test but semantically I wouldn't, since it basically means "we didn't get the exception we expected" and so that represents a programming error, instead of a test environment error.

这篇关于在Java中捕获通用异常?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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