Java Reference
In-Depth Information
Java API Exceptions and Errors
The exam objectives state that you should be able to “recognize situations that will
result in any of the following being thrown,” and also “understand which of these are
thrown by the virtual machine and recognize situations in which others should be thrown
programmatically”
This section covers the details of each of the following
Throwable
types, all declared in
the
java.lang
package:
ArrayIndexOutOfBoundsException
This exception is thrown by the JVM when your code
uses an illegal index to access an array.
ClassCastException
This exception is thrown by the JVM when an attempt is made to
cast an object reference to a subclass of which it is not an instance.
IllegalArgumentException
This exception is thrown programmatically to indicate that a
method has been passed an illegal or inappropriate argument.
IllegalStateException
This exception is thrown programmatically when a method has
been invoked while the program is in an inappropriate state.
NullPointerException
This exception is thrown by the JVM when an attempt is made to
use a null reference where an object is required.
NumberFormatException
This exception is thrown programmatically when an attempt
is made to convert a string to a numeric type, but the string does not have the appropriate
format.
AssertionError
This exception is thrown by the JVM when an
assert
statement fails.
ExceptionInInitializerError
This exception is thrown by the JVM when an unex-
pected exception occurs in a static initializer.
StackOverflowError
This exception is thrown by the JVM when the method call stack
overfl ows.
NoClassDefFoundError
This exception is thrown by the JVM or
ClassLoader
when a
class needs to be loaded but no defi nition of the class can be found.
Note that you can programmatically throw any of these exceptions and errors, even
if an exception is typically thrown by the JVM. For example, if your code is aware
of a situation where an illegal array index is being used, you can instantiate a new
ArrayIndexOutOfBoundsException
object and throw it using the
throw
keyword. However,
this is not something commonly done in Java.
The following section briefl y discusses each of these types of exceptions and
demonstrates situations where they might be thrown.
Search WWH ::
Custom Search