Consider this pair of Throwable
:
IllegalAccessException
extends Exception
Thrown when an application tries to reflectively cr
The description already explains some of it: the Exception
is thrown when you use reflection to access a field or invoke a method that is not accessible; the Error
is thrown when you do so directly (and for some reason the compiler did not have the chance to catch it - for example when you have an old version of a class file around, in which the field or method you're trying to use is private).
An Error
normally indicates that there is something really wrong - there is almost certainly a bug in the software. You should never try to catch Error
s. If you are catching the XXXException
, there is no immediate reason to also catch the XXXError
. The documentation of Error
says:
An Error is a subclass of Throwable that indicates serious problems that a reasonable application should not try to catch. Most such errors are abnormal conditions. The ThreadDeath error, though a "normal" condition, is also a subclass of Error because most applications should not try to catch it.
A method is not required to declare in its throws clause any subclasses of Error that might be thrown during the execution of the method but not caught, since these errors are abnormal conditions that should never occur.
An example to generate IllegalAccessException
: Via reflection, lookup a private method in a class and try to call it.
An example to generate IllegalAccessError
: Create two classes and save them in two source files A.java
and B.java
. In class A
, create a public method, and in class B
, call that method. Compile the source files. Now, edit A.java
and make the method private, and recompile only A.java
(not B.java
). Now try running again; B
will try to call the method and throw an IllegalAccessError
.
There are other pairs of XXXException
/ XXXError
that seem related, but they don't always have exactly matching names; for example ClassNotFoundException
/ NoClassDefFoundError
.