Consider this pair of Throwable
:
IllegalAccessException
extends Exception
Thrown when an application tries to reflectively cr
Can someone give a code example where each is thrown?
The IllegalAccessException
is thrown when you try to use reflection to invoke a method or read or write a field that is forbidden by the Java visibility rules.
An IllegalAccessError
cannot be thrown by consistently compiled Java code. It occurs when for example, you load a class that attempts to invoke a method or read or write a field in another class that is forbidden by the Java visibility rules. This is something that the compiler would normally prevent, so this means there is something seriously wrong with the classes. At any rate, this is considered to be an "error"; i.e. not recoverable, and the classloader will refuse to load the offending class(es).
Does the similarity in name imply relationship between the two, or is it just pure coincidence?
There is a clear relationship between the two. The difference is the circumstances in which the two occur.
Are there other XXXError and XXXException combo? How are the pairs related to each other?
Pass. Check the javadocs.
If you explicitly try to catch one in an Exception/Error pair, should you also catch the other?
Probably not. The XXXError and XXXException generally occur in different circumstances. (This certainly applies to the reflective vs. classloader ones.)
Besides, as a general rule you should not attempt to catch and recover from subtypes of Error
. The whole point of separating Error
from Exception
is to distinguish the non-recoverable and (potentially) recoverable exceptions.
In this case, there is nothing that a normal application can do in the way of recovering from the IllegalAccessError
. If you attempt to repeat the classloader operation that caused the problem, it will just happen again.