I have a method which I would like to call via reflection. The method does some various checks on its arguments and can throw NullPointer and IllegalArgument exceptions.
Calling the method via Reflection also can throw IllegalArgument and NullPointer exceptions which need to be caught. Is there a way to determine whether the exception is caused by the reflection Invoke method, or by the method itself?
A checked exception is caught at compile time whereas a runtime or unchecked exception is, as it states, at runtime. A checked exception must be handled either by re-throwing or with a try catch block, whereas an unchecked isn't required to be handled.
A checked exception in Java represents a predictable, erroneous situation that can occur even if a software library is used as intended. For example, if a developer tries to access a file, the Java IO library forces them to deal with the checked FileNotFoundException.
ClassNotFoundException, IOException, SQLException etc are the examples of the checked exceptions.
If the method itself threw an exception, then it would be wrapped in a InvocationTargetException.
Your code could look like this
try
{
method . invoke ( args ) ;
}
catch ( IllegalArgumentException cause )
{
// reflection exception
}
catch ( NullPointerException cause )
{
// reflection exception
}
catch ( InvocationTargetException cause )
{
try
{
throw cause . getCause ( ) ;
}
catch ( IllegalArgumentException c )
{
// method exception
}
catch ( NullPointerException c )
{
//method exception
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With