Consider this pair of Throwable:
IllegalAccessExceptionextends ExceptionThrown when an application tries to reflectively create an instance (other than an array), set or get a field, or invoke a method, but the currently executing method does not have access to the definition of the specified class, field, method or constructor.
IllegalAccessErrorext IncompatibleClassChangeError ext LinkageError ext ErrorThrown if an application attempts to access or modify a field, or to call a method that it does not have access to.
Normally, this error is caught by the compiler; this error can only occur at run time if the definition of a class has incompatibly changed.
Questions
- Can someone give a code example where each is thrown?
- Does the similarity in name imply relationship between the two, or is it just pure coincidence?
- Are there other
XXXErrorandXXXExceptioncombo? How are the pairs related to each other? - If you explicitly
trytocatchone in anException/Errorpair, should you alsocatchthe other?
The
IllegalAccessExceptionis 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
IllegalAccessErrorcannot 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).There is a clear relationship between the two. The difference is the circumstances in which the two occur.
Pass. Check the javadocs.
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 separatingErrorfromExceptionis 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.