IndexOutOfBoundsException抛出的UndeclaredThrowableException

Nat*_*ill 8 java proxy-classes

我正在使用装饰器模式List<WebElement>.这个装饰的部分需要使用代理.

当我get(index)使用超出范围的索引调用时,它会抛出一个IndexOutOfBounds异常,然后由代理捕获,并用一个包装UndeclaredThrowableException.

我的理解是它应该在它被检查的异常时才这样做. IndexOutOfBounds是一个未经检查的异常,为什么它被包裹?

即使我添加throws IndexOutOfBounds到我的invoke函数,它仍然会被包装.

这是我的代码:

@SuppressWarnings("unchecked")
public WebElementList findWebElementList(final By by){
    return new WebElementList(
            (List<WebElement>) Proxy.newProxyInstance(this.getClass().getClassLoader(),
                    new Class<?>[] { List.class }, new InvocationHandler() {
        // Lazy initialized instance of WebElement
        private List<WebElement> webElements;

        public Object invoke(Object proxy, Method method, Object[] args)
                throws Throwable {
            if (webElements == null) {
                webElements = findElements(by);
            }
            return method.invoke(webElements, args);
        }
    }), driver);
}
Run Code Online (Sandbox Code Playgroud)

这是我的堆栈跟踪的一部分:

java.lang.reflect.UndeclaredThrowableException
at com.sun.proxy.$Proxy30.get(Unknown Source)
at org.lds.ldsp.enhancements.WebElementList.get(WebElementList.java:29)
...
Caused by: java.lang.IndexOutOfBoundsException: Index: 1, Size: 1
at java.util.ArrayList.rangeCheck(ArrayList.java:604)
at java.util.ArrayList.get(ArrayList.java:382)
... 41 more
Run Code Online (Sandbox Code Playgroud)

Zor*_*org 9

Vic Jang是对的.您需要在try-catch中包装调用并重新抛出内部异常.

try {
  return method.invoke(webElements, args);
} catch (InvocationTargetException ite) {
  throw ite.getCause();
}
Run Code Online (Sandbox Code Playgroud)

原因是"Method.invoke"在InvocationTargetException中包含了方法代码中抛出的那些异常.

java.lang.reflect.Method中:

抛出:
...
InvocationTargetException - 如果基础方法抛出异常.

java.lang.reflect.InvocationTargetException:

InvocationTargetException是一个已检查的异常,它包装被调用的方法或构造函数抛出的异常.

代理对象的类在其"throws"中没有声明InvocationTargetException.这导致UndeclaredThrowableException.