try { Method method = MyClass.class.getMethod("myMethod"); Object result = method.invoke(myObject); } catch (InvocationTargetException e) { Throwable cause = e.getCause(); System.out.println("Exception thrown: " + cause); }
try { Constructor constructor = MyClass.class.getConstructor(int.class); MyClass myObject = (MyClass) constructor.newInstance(10); } catch (InvocationTargetException e) { Throwable cause = e.getCause(); System.out.println("Exception thrown: " + cause); }In this example, we are trying to create a new instance of the class MyClass using reflection. If an exception is thrown during the constructor invocation, we catch the InvocationTargetException and call the getTargetException method to retrieve the cause of the exception. Package Library: The java.lang.reflect package is the library that contains the InvocationTargetException class along with other reflection-related classes in Java.