Catch a generic exception in Java?

前端 未结 7 1157
不知归路
不知归路 2020-12-11 14:26

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();         


        
相关标签:
7条回答
  • 2020-12-11 15:20

    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.

    0 讨论(0)
提交回复
热议问题