javaexceptioninvoke

Java: How do I catch an exception created inside the Method.invoke?


It seems like I can't catch exceptions in my code when the method was called from the Method.invoke method. How can catch it from inside the method itself?

void function() {
  try {
    // code that throws exception
  }
  catch( Exception e ) {
    // it never gets here!! It goes straight to the try catch near the invoke
  }
}

try {
  return method.invoke(callTarget, args);
}
catch( InvocationTargetException e ) {
  // exception thrown in code that throws exception get here!
}

Thanks!


Solution

  • One reason that you can't catch UnsatisfiedLinkError with Exception is that UnsatisfiedLinkError is not a subclasses of Exception. In fact, it is a subclass of Error.

    You should be careful about catching Error exceptions. They almost always indicate that something really bad has happened, and in most cases it is not possible to recover from them safely. For instance, an UnsatisfiedLinkError means that the JVM can't find a native library ... and that whatever depended on that library is (probably) unusable. Generally speaking. Error exceptions should be treated as fatal errors.