Java provides numerous exception classes, all of which are descendants of the Throwable
class. All of them allow programs to differentiate among the
various types of exceptions that can occur during the execution of a program.
Throwable
The Throwable
class is the superclass of all errors and
exceptions in Java.
Only objects that are instances of this class or one of its subclasses
throw
statement, andcatch
clause.Exception
An instance of Exception
indicates a condition that an
application may need to catch.
The class Exception
and any subclasses that are not also
subclasses of RuntimeException
are called checked
exceptions.
Checked exceptions need to be declared in a method or constructor's throws
clause if
RuntimeException
RuntimeException
is the superclass of those exceptions
that can be thrown during the normal operation of the Java Virtual Machine.
RuntimeException and its subclasses are unchecked exceptions, which means that they do not need to be
declared in a method or constructor's throws
clause.
Most runtime exceptions can be avoided by checking certain conditions.
NullPointerException
checks if reference variable is null
before invoking a method on it.
public static Integer getHead(List<Integer> list) {
if (list != null)
return list.get(0);
return null;
}
ArrayIndexOutOfBoundsException
checks if the array index is
less than the array length.
public static int getValue(int[] array, int index) {
if (index < array.length)
return array[index];
return -1;
}
Error
extends the Throwable class.
An Error
error is thrown by JVM. It
indicates a serious problem that an application should not try to catch.
Here are a few examples:
OutOfMemoryError
is thrown when
the JVM runs out of memory and cannot clean the memory using garbage collection.StackOverflowError
is thrown when
the memory allocated for the stack of the method calls is not enough to store another stack frame.NoClassDefFoundError
is thrown when the JVM cannot
find the definition of the class requested by the currently loaded class.AssertionError
is thrown when an assertion has failed.