UndeclaredThrowableException thrown by IndexOutOfBoundsException

I am using a decorator template for List<WebElement> . Part of this decoration involves the use of a proxy.

When I call get(index) with an index that is out of scope, it throws an IndexOutOfBounds exception, which is then caught by the proxy and is IndexOutOfBounds using an UndeclaredThrowableException .

I understand that he should only do this if it is a checked exception. IndexOutOfBounds is an unchecked exception, so why does it get wrapped?

It will still be wrapped even if I add throws IndexOutOfBounds to my invoke function.

Here is my code:

 @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); } 

Here is part of my stacktrace:

 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 
+6
source share
2 answers
Vick Jang is right. You need to wrap the call in try-catch and rebuild the internal exception.
 try { return method.invoke(webElements, args); } catch (InvocationTargetException ite) { throw ite.getCause(); } 

The reason is that the Method.invoke method includes those exceptions that are thrown into the method code in the InvocationTargetException.

java.lang.reflect.Method:

It produces:
...
InvocationTargetException - if the base method throws an exception.

java.lang.reflect.InvocationTargetException:

InvocationTargetException is an exception that wraps an exception caused by the called method or constructor.

The proxy class does not have an InvocationTargetException thrown among its throws. This results in an UndeclaredThrowableException.

+7
source

I don't have enough reputation for comment. Your problem seems very similar to this

You can look at the solution there and see if it works.

In short, you need to wrap method.invoke again in try{} , catch exception and throw again.

+1
source

Source: https://habr.com/ru/post/957065/


All Articles