[Java] – Treating Reflection Exceptions

We need take more care when we work with reflections because we can find the exceptions which we normally find in a compilation time. With reflections you are manipulating classes and objects, thus it can be happening in execution time . 

Below are the some common exceptions which we can have :

  • NoSuchFieldException :

Doesn’t have a field of a specified name.

+ API : https://docs.oracle.com/javase/8/docs/api/java/lang/NoSuchFieldException.html

Example :

Screen Shot 2016-06-06 at 4.58.35 PM.png

  • NoSuchMethodException: 

Thrown when a particular method cannot be found.

+ API : https://docs.oracle.com/javase/8/docs/api/java/lang/NoSuchFieldException.html

Screen Shot 2016-06-06 at 4.57.38 PM

  • IllegalArgumentException: 
Thrown to indicate that a method has been passed an illegal or inappropriate argument. For example, in this case you can treat converting the argument type or adding a missed value, among others treatments.

+ API : https://docs.oracle.com/javase/8/docs/api/java/lang/IllegalArgumentException.html

Screen Shot 2016-06-06 at 5.41.45 PM

  • IllegalAccessException: 
Thrown to indicate that a method has been passed an illegal or inappropriate argument.

Screen Shot 2016-06-06 at 5.43.27 PM

InvocationTargetException

ATTENTION HERE

It is the case which we really need speak about. Why?

This situation happen when the method or the constructor throw an exception. You will receive it, but the real exception is inside of it. It’s like the real exception is encapsulated inside the InvocationTargetException .

Use it for take the real exception  : ex.getTargetException()
Let’s go to see some examples for understand this :
Screen Shot 2016-06-06 at 5.45.17 PM.png
If you look the real exception was thrown for the MethodA and is a RuntimeException.
Screen Shot 2016-06-06 at 5.47.34 PM
Now, you can see this 😛 

 

 

 

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s