嗯,我试着去理解和解读导致它的原因,但我就是不明白:

在我的代码中有这样的代码:

 try{
 ..
 m.invoke(testObject);
 ..
 } catch(AssertionError e){
 ...
 } catch(Exception e){
 ..
 }

Thing is that, when it tries to invoke some method it throws InvocationTargetException instead of some other expected exception (specifically ArrayIndexOutOfBoundsException). As I actually know what method is invoked I went straight to this method code and added a try-catch block for the line that suppose to throw ArrayIndexOutOfBoundsException and it really threw ArrayIndexOutOfBoundsException as expected. Yet when going up it somehow changes to InvocationTargetException and in the code above catch(Exception e) e is InvocationTargetException and not ArrayIndexOutOfBoundsException as expected.

是什么导致了这样的行为或者我如何检查这样的事情?


当前回答

您可以使用getCause()方法与原始异常类进行比较,如下所示:

try{
  ...
} catch(Exception e){
   if(e.getCause().getClass().equals(AssertionError.class)){
      // handle your exception  1
   } else {
      // handle the rest of the world exception 
   }
} 

其他回答

这将打印特定方法中的精确代码行,当调用该方法时,会引发异常:

try {

    // try code
    ..
    m.invoke(testObject);
    ..

} catch (InvocationTargetException e) {

    // Answer:
    e.getCause().printStackTrace();
} catch (Exception e) {

    // generic exception handling
    e.printStackTrace();
}

问题还可能是targetSdkVersion升级了,并且您使用了已弃用的Gradle清单特性。尝试再次降低targetSdkVersion,看看它是否有效。在我的例子中,它是targetSdkVersion 31 -> 30

如果底层方法(使用Reflection调用的方法)抛出异常,则抛出此异常。

因此,如果反射API调用的方法抛出异常(例如运行时异常),反射API将把异常包装到InvocationTargetException中。

那个InvocationTargetException可能正在封装你的ArrayIndexOutOfBoundsException。在使用反射时,没有预先说明该方法可以抛出什么——因此,与使用抛出异常方法不同,所有异常都被捕获并封装在InvocationTargetException中。

则抛出异常

InvocationTargetException—如果底层方法抛出异常。

因此,如果用反射API调用的方法抛出异常(例如运行时异常),反射API将把异常包装到InvocationTargetException中。