Java Exception Handling Overview
Java Exception Handling Overview
3.1 EXCEPTIONS
An exception is an unexpected event, which may occur during the execution of a program
(at run time), to disrupt the normal flow of the program’s instructions. This leads to the
abnormal termination of the program, which is not always recommended.
Therefore, these exceptions are needed to be handled. The exception handling in java is
one of the powerful mechanisms to handle the runtime errors so that normal flow of the
application can be maintained.
An exception may occur due to the following reasons. They are.
Invalid data as input.
Network connection may be disturbed in the middle of communications
JVM may run out of memory.
File cannot be found/opened.
These exceptions are caused by user error, programmer error, and physical resources.
Based on these, the exceptions can be classified into three categories.
Checked exceptions − A checked exception is an exception that occurs at the compile
time, also called as compile time (static time) exceptions. These exceptions cannot
be ignored at the time of compilation. So, the programmer should handle these
exceptions.
Unchecked exceptions − An unchecked exception is an exception that occurs at run
time, also called as Runtime Exceptions. These include programming bugs, such as
logic errors or improper use of an API. Runtime exceptions are ignored at the time of
compilation.
Errors − Errors are not exceptions, but problems may arise beyond the control of the
user or the programmer. Errors are typically ignored in your code because you can
rarely do anything about an error. For example, if a stack overflow occurs, an error
will arise. They are also ignored at the time of compilation.
Error: An Error indicates serious problem that a reasonable application should not
try to catch.
Exception: Exception indicates conditions that a reasonable application might try to
catch.
3.2 EXCEPTION HIERARCHY
The [Link] class is the base class for all exception classes. All exception and
errors types are sub classes of class Throwable, which is base class of hierarchy. One branch
is headed by Exception. This class is used for exceptional conditions that user programs
should catch. NullPointerException is an example of such an exception. Another branch,
Error are used by the Java run-time system(JVM) to indicate errors having to do with the
run- time environment itself(JRE). StackOverflowError is an example of such an error.
Errors are abnormal conditions that happen in case of severe failures, these are not
handled by the Java programs. Errors are generated to indicate errors generated by the
runtime environment. Example: JVM is out of memory. Normally, programs cannot recover
from errors.
The Exception class has two main subclasses: IOException class and RuntimeException
Class.
Exceptions Methods
Method Description
public String getMessage() Returns a detailed message about the exception that has
occurred. This message is initialized in the Throwable
constructor.
public Throwable getCause() Returns the cause of the exception as represented by a
Throwable object.
public String toString() Returns the name of the class concatenated with the re-
sult of getMessage().
public void printStackTrace() Prints the result of toString() along with the stack trace to
[Link], the error output stream.
public StackTraceElement [] Returns an array containing each element on the stack
trace. The element at index 0 represents the top of the
getStackTrace()
call stack, and the last element in the array represents the
method at the bottom of the call stack.
public Throwable Fills the stack trace of this Throwable object with the
current stack trace, adding to any previous information
fillInStackTrace()
in the stack trace.
Exception handling in java uses the following Keywords
1. try
2. catch
3. finally
4. throw
5. throws
The try/catch block is used as follows:
try {
// block of code to monitor for errors
// the code you think can raise an exception
}
catch (ExceptionType1 exOb) {
// exception handler for ExceptionType1
}
catch (ExceptionType2 exOb) {
// exception handler for ExceptionType
}
// optional
finally {
// block of code to be executed after try block ends
}
Throwing and catching exceptions
Catching Exceptions
A method catches an exception using a combination of the try and catch keywords. The
program code that may generate an exception should be placed inside the try/catch block. The
syntax for try/catch is depicted as below−
Syntax
try {
// Protected code
} catch (ExceptionName e1) {
// Catch block
}
The code which is prone to exceptions is placed in the try block. When an exception
occurs, that exception is handled by catch block associated with it. Every try block should
be immediately followed either by a catch block or finally block.
A catch statement involves declaring the type of exception that might be tried to catch. If
an exception occurs, then the catch block (or blocks) which follow the try block is checked.
If the type of exception that occurred is listed in a catch block, the exception is passed to the
catch block similar to an argument that is passed into a method parameter.
To illustrate the try-catch blocks the following program is developed.
class Exception_example {
public static void main(String args[])
{
int a,b;
try { // monitor a block of code.
a = 0;
b = 10 / a; //raises the arithmetic exception
[Link](“Try block.”);
}
catch (ArithmeticException e)
{ // catch divide-by-zero error
[Link](“Division by zero.”);
}
[Link](“After try/catch block.”);
}
}
Output:
Division by zero.
After try/catch block.
Multiple catch Clauses
In some cases, more than one exception could be raised by a single piece of code. To
handle this multiple exceptions, two or more catch clauses can be specified. Here, each catch
block catches different type of exception. When an exception is thrown, each catch statement
is inspected in order, and the first one whose type matches that of the exception is executed.
After one catch statement executes, the others are bypassed, and execution continues after the
try/catch block. The following example traps two different exception types:
class MultiCatch_Example {
public static void main(String args[]) {
try {
int a,b;
a = [Link];
[Link](“a = “ + a);
b = 10 / a; //may cause division-by-zero error
int arr[] = { 10,20 };
c[5] =100;
}
catch(ArithmeticException e)
{
[Link](“Divide by 0: “ + e);
}
catch(ArrayIndexOutOfBoundsException e)
{
[Link](“Array index oob: “ + e);
}
[Link](“After try/catch blocks.”);
}
}
Here is the output generated by the execution of the program in both ways:
C:\>java MultiCatch_Example
a=0
Divide by 0: [Link]: / by zero
After try/catch blocks.
C:\>java MultiCatch_Example arg1
a=1
Array index oob: [Link]
After try/catch blocks.
While the multiple catch statements is used, it is important to remember that exception
subclasses must come before their superclasses. A catch statement which uses a superclass
will catch exceptions of that type plus any of its subclasses. Thus, a subclass would never
be reached if it came after its superclass. And also, in Java, unreachable code is an error. For
example, consider the following program:
class MultiCatch_Example {
public static void main(String args[]) {
try {
int a,b;
a = [Link];
[Link](“a = “ + a);
b = 10 / a; //may cause division-by-zero error
int arr[] = { 10,20 };
c[5] =100;
}
catch(Exception e) {
[Link](“Generic Exception catch.”);
}
catch(ArithmeticException e)
{
[Link](“Divide by 0: “ + e);
}
catch(ArrayIndexOutOfBoundsException e)
{
[Link](“Array index oob: “ + e);
}
[Link](“After try/catch blocks.”);
}
}
The exceptions such as ArithmeticException, and ArrayIndexOutOfBoundsException are
the subclasses of Exception class. The catch statement after the base class catch statement is
raising the unreachable code exception.
Nested try block
Sometimes a situation may arise where a part of a block may cause one error and the entire
block itself may cause another error. In such cases, exception handlers have to be nested.
try
{
statement 1;
statement 2;
try
{
statement 1;
statement 2;
}
catch(Exception e)
{
}
}
catch(Exception e)
{
}
....
The following program is an example for Nested try statements.
class Nestedtry_Example{
public static void main(String args[]){
try{
try{
[Link](“division”);
int a,b;
a=0;
b =10/a;
}
catch(ArithmeticException e)
{
[Link](e);
}
try
{
int a[]=new int[5];
a[6]=3;
}
catch(ArrayIndexOutOfBoundsException e)
{
[Link](e);
}
[Link](“other statement);
}
catch(Exception e)
{
[Link](“handeled”);}
[Link](“normal flow..”);
}
}
Throw keyword
The Java throw keyword is used to explicitly throw an exception. The general form of
throw is shown below:
throw ThrowableInstance;
Here, ThrowableInstance must be an object of type Throwable or a subclass of
Throwable. Primitive types, such as int or char, as well as non-Throwable classes, such as
String and Object, cannot be used as exceptions.
There are two ways to obtain a Throwable object:
1. using a parameter in a catch clause
2. creating one with the new operator.
The following program explains the use of throw keyword.
public class TestThrow1{
static void validate(int age){
try{
if(age<18)
throw new ArithmeticException(“not valid”);
else
[Link](“welcome to vote”);
}
Catch(ArithmeticException e)
{
[Link](“Caught inside ArithmeticExceptions.”);
throw e; // rethrow the exception
}
}
public static void main(String args[]){
try{
validate(13);
}
Catch(ArithmeticException e)
{
[Link](“ReCaught ArithmeticExceptions.”);
}
}
}
The flow of execution stops immediately after the throw statement and any subsequent
statements that are not executed. The nearest enclosing try block is inspected to see if it has
a catch statement that matches the type of exception. If it does find a match, control is
transferred to that statement. If not, then the next enclosing try statement is inspected, and
so on. If no matching catch is found, then the default exception handler halts the program and
prints the stack trace.
The Throws/Throw Keywords
If a method does not handle a checked exception, the method must be declared using
the throws keyword. The throws keyword appears at the end of a method’s signature.
The difference between throws and throw keywords is that, throws is used to postpone the
handling of a checked exception and throw is used to invoke an exception explicitly.
The following method declares that it throws a Remote Exception −
Example
import [Link].*;
public class throw_Example1 {
public void function(int a) throws RemoteException {
// Method implementation
throw new RemoteException();
} // Remainder of class definition
}
A method can declare that it throws more than one exception, in which case the
exceptions are declared in a list separated by commas. For example, the following method
declares that it throws a RemoteException and an ArithmeticException −
import [Link].*;
public class throw_Example2 {
public void function(int a) throws RemoteException,ArithmeticException {
// Method implementation
}
// Remainder of class definition
}
The Finally Block
The finally block follows a try block or a catch block. A finally block of code always
executes, irrespective of the occurrence of an Exception. A finally block appears at the end
of the catch blocks that follows the below syntax.
Syntax
try {
// Protected code
} catch (ExceptionType1 e1) {
// Catch block
} catch (ExceptionType2 e2) {
// Catch block
}
finally {
// The finally block always executes.
}
Example
public class Finally_Example {
public static void main(String args[]) {
try {
int a,b;
a=0;
b=10/a;
} catch (ArithmeticException e) {
[Link](“Exception thrown :” + e);
}finally {
[Link](“The finally block is executed”);
}
}
}
Points to remember:
A catch clause cannot exist without a try statement.
It is not compulsory to have finally clauses whenever a try/catch block is present.
The try block cannot be present without either catch clause or finally clause.
Any code cannot be present in between the try, catch, finally blocks.
3.3 BUILT-IN EXCEPTIONS
Built-in exceptions are the exceptions which are available in Java libraries. These
exceptions are suitable to explain certain error situations. Below is the list of important
built-in exceptions in Java.
Exceptions Description
Arithmetic Exception It is thrown when an exceptional condition has oc-
curred in an arithmetic operation.
Array Index Out Of Bound It is thrown to indicate that an array has been accessed
Exception with an illegal index. The index is either negative or
greater than or equal to the size of the array.
ClassNotFoundException This Exception is raised when we try to access a class
whose definition is not found.
FileNotFoundException This Exception is raised when a file is not accessible
or does not open.
IOException It is thrown when an input-output operation failed or
interrupted.
InterruptedException It is thrown when a thread is waiting, sleeping, or do-
ing some processing, and it is interrupted.
NoSuchFieldException It is thrown when a class does not contain the field (or
variable) specified.
NoSuchMethodException It is thrown when accessing a method which is not
found.
NullPointerException This exception is raised when referring to the members
of a null object. Null represents nothing.
NumberFormatException This exception is raised when a method could not con-
vert a string into a numeric format.
RuntimeException This represents any exception which occurs during
runtime.
StringIndexOutOfBoundsEx- It is thrown by String class methods to indicate that an
ception index is either negative than the size of the string
The following Java program explains NumberFormatException
class NumberFormat_Example
{
public static void main(String args[])
{
try {
int num = [Link] (“hello”) ;
[Link](num);
}
catch(NumberFormatException e) {
[Link](“Number format exception”);
}
}
}
The following Java program explains StackOverflowError exception.
class Example {
public static void main(String[] args)
{
fun1();
}
public static void fun1()
{
fun2();
}
public static void fun2()
{
fun1();
}
}
Output:
Exception in thread “main” [Link]
at Example.fun2([Link])
at Example.fun1([Link])
3.4 USER DEFINED EXCEPTION IN JAVA
Java allows the user to create their own exception class which is derived from
builtin class Exception. The Exception class inherits all the methods from the class
Throwable. The Throwable class is the superclass of all errors and exceptions in the Java
language. It contains a snapshot of the execution stack of its thread at the time it was
created. It can also contain a message string that gives more information about the error.
The Exception class is defined in [Link] package.
User defined exception class must inherit Exception class.
The user defined exception can be thrown using throw keyword.
Syntax:
class User_defined_name extends Exception{
………..
}
Some of the methods defined by Throwable are shown in below table.
Methods Description
Throwable fillInStackTrace( ) Fills in the execution stack trace and returns a
Throwable object.
String getLocalizedMessage() Returns a localized description of the exception.
String getMessage() Returns a description of the exception.
void printStackTrace( ) Displays the stack trace.
String toString( ) Returns a String object containing a description
of the Exception.
StackTraceElement[ ]get Returns an array that contains the stack trace, one
StackTrace( ) element at a time, as an array of StackTraceEle-
ment.
Two commonly used constructors of Exception class are:
Exception() - Constructs a new exception with null as its detail message.
Exception(String message) - Constructs a new exception with the specified detail
message.
Example:
//creating a user-defined exception class derived from Exception class
public class MyException extends Exception
{
public String toString(){ // overriding toString() method
return “User-Defined Exception”;
}
public static void main(String args[]){
MyException obj= new MyException();
try
{
throw new MyException(); // customized exception is raised
}
/*Printing object e makes a call to toString() method which
catch(MyException e)
returns String error message*/
{
[Link](“Exception handled - “+ e);
}
}
}
Sample Output:
Exception handled - User-Defined Exception
In the above example, a custom defined exception class MyException is created by
inheriting it from Exception class. The toString() method is overridden to display the
customized method on catch. The MyException is raised using the throw keyword.
Example:
Program to create user defined exception that test for odd numbers.
import [Link];
class OddNumberException extends Exception
{
OddNumberException() //default constructor
{
super(“Odd number exception”);
}
OddNumberException(String msg) //parameterized constructor
{
super(msg);
}
}
public class UserdefinedExceptionDemo{
public static void main(String[] args)
{
int num;
Scanner Sc = new Scanner([Link]); // create Scanner object to read input
[Link](“Enter a number : “);
num = [Link]([Link]());
try
{
if(num%2 != 0) // test for odd number
throw(new OddNumberException()); // raise the exception if number is odd
else
[Link](num + “ is an even number”);
}
catch(OddNumberException Ex)
{
[Link](“\n\tError : “ + [Link]());
}
}
}
Sample Output1:
Enter a number : 11
Error : Odd number exception
Sample Output2:
10 is an even number
Odd Number Exception class is derived from the Exception class. To implement user
defined exception we need to throw an exception object explicitly. In the above example, If
the value of num variable is odd, then the throw keyword will raise the user defined exception
and the catch block will get execute.
3.5 CHAINED EXCEPTIONS
Chained Exceptions allows to relate one exception with another exception, i.e one
exception describes cause of another exception. For example, consider a situation in which
a method throws an ArithmeticException because of an attempt to divide by zero but the
actual cause of exception was an I/O error which caused the divisor to be zero. The method
will throw only ArithmeticException to the caller. So the caller would not come to know
about the actual cause of exception. Chained Exception is used in such type of situations.
Throwable constructors that supports chained exceptions are:
1. Throwable(Throwable cause) :- Where cause is the exception that causes the current
exception.
2. Throwable(String msg, Throwable cause) :- Where msg is the exception message and
cause is the exception that causes the current exception.
Throwable methods that supports chained exceptions are:
1. getCause() method :- This method returns actual cause of an exception.
2. initCause(Throwable cause) method :- This method sets the cause for the calling ex-
ception.
Example:
import [Link];
public class ChainedException
{
public static void divide(int a, int b)
{
if(b==0)
{
ArithmeticException ae = new ArithmeticException(“top layer”);
[Link]( new IOException(“cause”) );
throw ae;
}
else
{
[Link](a/b);
}
}
public static void main(String[] args)
{
try {
divide(5, 0);
}
catch(ArithmeticException ae) {
[Link]( “caught : “ +ae);
[Link](“actual cause: “+[Link]());
}
}
}
Sample Output:
caught : [Link]: top layer
actual cause: [Link]: cause
In this example, the top-level exception is ArithmeticException. To it is added a cause
exception, IOException. When the exception is thrown out of divide( ), it is caught by
main(). There, the top-level exception is displayed, followed by the underlying exception,
which is obtained by calling getCause( ).
3.6 STACK TRACE ELEMENT
The StackTraceElement class element represents a single stack frame which is a stack
trace when an exception occurs. Extracting stack trace from an exception could provide
useful information such as class name, method name, file name, and the source-code line
number. The getStackTrace( ) method of the Throwable class returns an array of
StackTraceElements.
StackTraceElement class constructor
StackTraceElement(String declaringClass, String methodName, String fileName, int
lineNumber)
This creates a stack trace element representing the specified execution point.
Stack Trace Element class methods
Method Description
boolean equals(Object obj) Returns true if the invoking StackTraceElement is the
same as the one passed in obj. Otherwise, it returns false.
String getClassName() Returns the class name of the execution point
String getFileName( ) Returns the filename of the execution point
int getLineNumber( ) Returns the source-code line number of the execution
point
String getMethodName( ) Returns the method name of the execution point
String toString( ) Returns the String equivalent of the invoking sequence
Example:
public class StackTraceEx{
public static void main(String[] args) {
try{
throw new RuntimeException(“go”); //raising an runtime exception
}
catch(Exception e){
[Link](“Printing stack trace:”);
//create array of stack trace elements
final StackTraceElement[] stackTrace = [Link]();
for (StackTraceElement s : stackTrace) {
[Link](“\tat “ + [Link]() + “.” + [Link]()
+ “(“ + [Link]() + “:” + [Link]() + “)”);
}
}
}
}
Sample Output:
Printing stack trace:
at [Link]([Link])
3.7 INPUT/OUTPUT BASICS
Java I/O (Input and Output) is used to process the input and produce the output. Java uses
the concept of stream to make I/O operation fast. All the classes required for input and output
operations are declared in [Link] package.
A stream can be defined as a sequence of data. The Input Stream is used to read data from
a source and the OutputStream is used for writing data to a destination.
Buffered Input Stream Contains methods to read bytes from the buffer (memory
area)
Byte Array Input Contains methods to read bytes from a byte array
Stream
Data Input Stream Contains methods to read Java primitive data types
Filter Input Stream Contains methods to read bytes from other input streams
which it uses as its basic source of data
Object Input Stream Contains methods to read objects
Piped Input Stream Contains methods to read from a piped output stream. A
piped input stream must be connected to a piped output
stream
Sequence Input Stream Contains methods to concatenate multiple input streams and
then read from the combined stream
Some of the useful methods of InputStream are listed below.
Method Description
public abstract int read() Reads the next byte of data from the input stream. It returns -1
throws IOException at the end of file.
public int available() Returns an estimate of the number of bytes that can be read
throws IOException from the current input stream.
public void close() Close the current input stream
throws IOException