Explain Java’s Built-in Exceptions, Creating Your Own Exception Subclasses In Java Explain
In This Topic & Blog Having Any Query Then Post your Comment and Suggestion Below

Java’s Built-in Exceptions
Inside the standard package
java.lang
, Java defines several exception classes. A few have
been used by the preceding examples. The most general of these exceptions are subclasses
of the standard type
RuntimeException
. As previously explained, these exceptions need
not be included in any method’s
throws
list. In the language of Java, these are called
unchecked exceptions because the compiler does not check to see if a method handles or
throws these exceptions. The unchecked exceptions defined in
java.lang
are listed in
Table 10-1. Table 10-2 lists those exceptions defined by
java.lang
that must be included
in a method’s
throws
list if that method can generate one of these exceptions and does
not handle it itself. These are called checked exceptions. Java defines several other types
of exceptions that relate to its various class libraries.
Exception
Meaning
ArithmeticException
Arithmetic error, such as divide-by-zero.
ArrayIndexOutOfBoundsException
Array index is out-of-bounds.
ArrayStoreException
Assignment to an array element of an incompatible type.
ClassCastException
Invalid cast.
EnumConstantNotPresentException
An attempt is made to use an undefined enumeration value.
IllegalArgumentException
Illegal argument used to invoke a method.
IllegalMonitorStateException
Illegal monitor operation, such as waiting on an unlocked
thread.
IllegalStateException
Environment or application is in incorrect state.
IllegalThreadStateException
Requested operation not compatible with current thread
state.
IndexOutOfBoundsException
Some type of index is out-of-bounds.
NegativeArraySizeException
Array created with a negative size.
NullPointerException
Invalid use of a null reference.
NumberFormatException
Invalid conversion of a string to a numeric format.
SecurityException
Attempt to violate security.
StringIndexOutOfBounds
Attempt to index outside the bounds of a string.
TypeNotPresentException
Type not found.
UnsupportedOperationException
An unsupported operation was encountered.
TABLE 10-1
Java’s Unchecked
RuntimeException
Subclasses Defined in
java.lang
Exception
Meaning
ClassNotFoundException
Class not found.
CloneNotSupportedException
Attempt to clone an object that does not implement the
Cloneable
interface.
IllegalAccessException
Access to a class is denied.
InstantiationException
Attempt to create an object of an abstract class or interface.
InterruptedException
One thread has been interrupted by another thread.
NoSuchFieldException
A requested field does not exist.
NoSuchMethodException
A requested method does not exist.
TABLE 10-2
Java’s Checked Exceptions Defined in
java.lang
Creating Your Own Exception Subclasses
Although Java’s built-in exceptions handle most common errors, you will probably want
to create your own exception types to handle situations specific to your applications. This
is quite easy to do: just define a subclass of
Exception
(which is, of course, a subclass of
Throwable
).
Your subclasses don’t need to actually implement anything—it is their existence
in the type system that allows you to use them as exceptions.
The
Exception
class does not define any methods of its own. It does, of course, inherit
those methods provided by
Throwable
.
Thus, all exceptions, including those that you create,
have the methods defined by
Throwable
available to them. They are shown in Table 10-3.
Method
Description
Throwable fillInStackTrace( )
Returns a
Throwable
object that contains a completed
stack trace. This object can be rethrown.
Throwable getCause( )
Returns the exception that underlies the current
exception. If there is no underlying exception,
null
is returned.
String getLocalizedMessage( )
Returns a localized description of the exception.
String getMessage( )
Returns a description of the exception.
StackTraceElement[ ] getStackTrace( )
Returns an array that contains the stack trace, one
element at a time, as an array of
StackTraceElement
.
The method at the top of the stack is the last method
called before the exception was thrown. This method
is found in the first element of the array. The
StackTraceElement
class gives your program access
to information about each element in the trace, such
as its method name.
Throwable initCause(Throwable
causeExc )
Associates causeExc with the invoking exception as a
cause of the invoking exception. Returns a reference
to the exception.
void printStackTrace( )
Displays the stack trace.
void printStackTrace(PrintStream
stream )
Sends the stack trace to the specified stream.
void printStackTrace(PrintWriter
stream )
Sends the stack trace to the specified stream.
void setStackTrace(StackTraceElement
elements [ ])
Sets the stack trace to the elements passed in
elements. This method is for specialized applications,
not normal use.
String toString( )
Returns a
String
object containing a description of the
exception. This method is called by
println( )
when
outputting a
Throwable
object.
TABLE 10-3
The Methods Defined by
Throwable
220
Part I:
The Java Language
You may also wish to override one or more of these methods in exception classes that you
create.
Exception
defines four constructors. Two were added by JDK 1.4 to support chained
exceptions, described in the next section. The other two are shown here:
Exception( )
Exception(String msg )
The first form creates an exception that has no description. The second form lets you specify
a description of the exception.
Although specifying a description when an exception is created is often useful, sometimes
it is better to override
toString( )
.
Here’s why: The version of
toString( )
defined by
Throwable
(and inherited by
Exception
)
first displays the name of the exception followed by a colon, which
is then followed by your description. By overriding
toString( )
, you can prevent the exception
name and colon from being displayed. This makes for a cleaner output, which is desirable in
some cases.
The following example declares a new subclass of
Exception
and then uses that subclass
to signal an error condition in a method. It overrides the
toString( )
method, allowing a
carefully tailored description of the exception to be displayed.
// This program creates a custom exception type.
class MyException extends Exception {
private int detail;
MyException(int a) {
detail = a;
}
public String toString() {
return "MyException[" + detail + "]";
}
}
class ExceptionDemo {
static void compute(int a) throws MyException {
System.out.println("Called compute(" + a + ")");
if(a > 10)
throw new MyException(a);
System.out.println("Normal exit");
}
public static void main(String args[]) {
try {
compute(1);
compute(20);
} catch (MyException e) {
System.out.println("Caught " + e);
}
}
}
This example defines a subclass of
Exception
called
MyException
. This subclass is quite
simple: it has only a constructor plus an overloaded
toString( )
method that displays the
value of the exception. The
ExceptionDemo
class defines a method named
compute( )
that
throws a
MyException
object. The exception is thrown when
compute( )
’s integer parameter
is greater than 10. The
main( )
method sets up an exception handler for
MyException
, then
calls
compute( )
with a legal value (less than 10) and an illegal one to show both paths through
the code. Here is the result:
Called compute(1)
Normal exit
Called compute(20)
Caught MyException[20]
Labels: Java - J2SE