What Are Important Methods of Java Exception Class?
What Are Important Methods of Java Exception Class?
Introduction
An unwanted event that disturb normal flow of the program is called exception. It is highly
recommended to handle exception and the main objective of exception handling is graceful termination
of the program.
1. String getMessage() – This method returns the message String of Throwable and the
message can be provided while creating the exception through it’s constructor.
2. String getLocalizedMessage() – This method is provided so that subclasses can
override it to provide locale specific message to the calling program. Throwable class
implementation of this method simply use getMessage() method to return the
exception message.
3. synchronized Throwable getCause() – This method returns the cause of the exception
or null if the cause is unknown.
4. String toString() – This method returns the information about Throwable in String format,
the returned String contains the name of Throwable class and localized message.
5. void printStackTrace() – This method prints the stack trace information to the standard
error stream, this method is overloaded and we can pass PrintStream or PrintWriter as
argument to write the stack trace information to the file or stream.
logger.error(ex);
Most of the time, we use finally block just to close the resources and sometimes we
forget to close them and get runtime exceptions when the resources are exhausted.
These exceptions are hard to debug and we might need to look into each place where
we are using that type of resource to make sure we are closing it. So java 7 one of the
improvement was try-with-resources where we can create a resource in the try
statement itself and use it inside the try-catch block. When the execution comes out of
try-catch block, runtime environment automatically close these resources. Sample of
try-catch block with this improvement is:
} catch (Exception e) {
e.printStackTrace();
Errors are mainly caused by the environment in which an application is running. For example,
OutOfMemoryError happens when JVM runs out of memory. Where as exceptions are mainly caused
by the application itself. For example, NullPointerException occurs when an application tries to
access null object.