Chapter 4 Exception Handling
Chapter 4 Exception Handling
- Compile-time Errors
- Run-time
Errors
All the syntax errors are detected by Java compiler. These errors are called
compile-time errors. Until and unless we clear compile program, byte-code
(.class file) will not be created for the examples of compile-time errors are
semicolon missing, mismatch of braces, use of undeclared variables etc.
After compiling a java program successfully, byte code is generated and then
that byte code given to the interpreter and it runs this .class file. But even then
sometimes the program generates wrong output. This happens due to incorrect
logic. This is called logical error (This type of error is to be corrected by
programmer by correcting the logic).
Also, sometimes program terminates due to errors like divide by zero. Both
these situations are referred to run-time errors. Some common run-time errors
are divide by zero, accessing element which is out of bound of array, converting
invalid string to a number etc.
Exception is a condition caused due to occurrence of run time error. This may
be due to violation of rules of Java language or due to constraints of the java
execution environment. While executing a program if exceptional condition
(like divide by zero) occurs, exception object is created by the java run time
system and is thrown. Exception can also be generated manually by a program
code.
In java, Throwable class woks as root for java’s error and exception hierarchy
as shown in following figure.
One more difference in Error and Exception is that Error is a critical condition
that cannot be handled by program code whereas Exception is exceptional
situation that can be handled by program code.
class WithoutException
{
public static void main(String args[ ])
{
int p, q, r, s;
p = 30;
q = 3;
r = 3;
s=p/(q-r);
System.out.println("Result is "+s);
System.out.println("At the end of try block");
System.out.println("You should not divide a number by 0");
System.out.println("At the end of catch block");
System.out.println("At the end of main method");
}
}
4.1.1 Process of handling exception
If exception object is not caught and handled properly, program displays error
message and terminates its execution abruptly. If we want to execute remaining
part of the program (in such situation), we should handle the exception thrown
by the program. This process involves various tasks as,
This can be achieved through two blocks -one for detecting error situation &
throwing the exception and other for catching the exception & taking suitable
action. These two blocks are referred as try block and catch black respectively.
They are shown in following figure.
Syntax for defining try block and catch block is given below.
try
{
Statements that may generate/cause exception
}
catch(Exception-type obj-name)
{
Statements for processing the caught exception
}
int a[]={1,2,3};
try
{
s=p/(q-r);//generate exception ArithmeticException
System.out.println(a[4]);
System.out.println(s);
}
catch(Exception e)
{
System.out.println(“divide by zero”);//handle
}
Try block
We can use keyword try for defining a ‘try block’ and keyword catch for
defining ‘catch block’.
Java try block is used to enclose the code that might throw an exception.
It must be used within the method.
Java catch block is used to handle the Exception by declaring the type of
exception within the parameter.
The declared exception must be the parent class exception ( i.e.,
Exception) or the generated exception type. However, the good approach
is to declare the generated type of exception.
The catch block must be used after the try block only. You can use
multiple catch block with a single try block.
Multiple statements may also be written in catch block for handling the
caught exception.
As observed in the above syntax, catch block looks like a method accepting one
parameter. If this parameter matches with the thrown exception object,
statements in the catch block are executed. Otherwise default exception handler
of java run-time environment will terminate the program execution.
Example 1:
class ExceptionEx1
{
public static void main(String args[ ])
{
int p, q, r, s;
p = 30;
q = 3;
r = 3;
try
{
s=p/(q-r);
System.out.println("Result is :"+s);
System.out.println("At the end of try block");
}
catch(ArithmeticException e)
{
System.out.println("You should not divide a number by 0");
System.out.println("At the end of catch block");
}
System.out.println("At the end of main method");
s=p/(q+r);
System.out.println("Result is :"+s);
}
}
Example 2:
class ExceptionEx2
{
public static void main(String args[ ])
{
int a[]={12,34,44,14};
int i;
System.out.println("Array elements are:");
try
{
for(i=0;i<8;i++)
{
System.out.println(a[i]);
}
}
catch(Exception e)
{
System.out.println(e);
}
System.out.println("Thank you for using this program");
}
}
We may use try block within another try block. This concept is called nested
try block. Each try block requires at least one matching catch block.
Syntax:
try
{
statement 1;
statement 2;
try
{
statement 1;
statement 2;
}
catch(Exception e)
{
}
}
catch(Exception e)
{
}
Example:
class ExceptionEx3
{
int a[]={12,34,44,14};
int i, p, q, r, s;
p = 30;
q = 3;
r = 3;
for(i=0;i<=4;i++)
System.out.println(a[i]);
try//inner try
s = p/(q-r);
System.out.println("Result is "+s);
It may happen that statements in try block may create different exceptional
situations. So, a single try block may have multiple catch blocks for catching
try
catch(Exception_type1 e)
{------}
catch(Exception_Type2 e)
{---------}
catch(Exception_type3 e)
{----------}
Example:
class ExceptionEx4
{
public static void main(String args[ ])
{
int a[]={12,34,44,14};
int i, p, q, r;
p = 30;
q = 3;
r = 3;
try
{
a[5] = p/(q-r);
System.out.println("Result of division is stored in array");
}
catch(ArithmeticException e)
{
System.out.println("You should not divide a number by 0");
System.out.println("At the end of catch block 1");
}
catch(ArrayIndexOuyOfBoundsException e)
{
System.out.println("hiii");
}
System.out.println("At the end of main method");
}
}
4.1.4 Using finally statement
We may have a finally block after all the catch blocks (or even we may have try
block immediately followed by finally block). The finally block is always
executed regardless of whether the exception is thrown or not. It may happen
that there are multiple catch blocks, exception is thrown by try block and not a
single catch block is able to catch the exception. In such situation also, finally
block is executed. Even if any catch block is executed, finally block is also
executed. These characteristics can be easily figured out in the following figure.
Figure 4.3: finally block in Exception Handling
try
{
- try
- {
- -
} -
catch(Exception_Type e) -
{ }
-
- finally
} {
finally -
{ -
- }
-
}
Due to all these characteristics of finally block, it is generally used to perform
housekeeping operations like closing file handles, freeing the allocated
resources etc.
Following example program shows methods that exits in different ways, but
each executes their finally block.
Example:
class ExceptionEx6
{
static void method1(int x, int y)
{
int z;
try
{
z = x/y;
System.out.println("Result of division is: "+z);
}
catch(ArithmeticException e)
{
System.out.println("You should not divide a number by zero");
}
finally
{
System.out.println("Finally block is always executed");
}
}
public static void main(String args[ ])
{
method1(10,5);
method1(20,0);
}
}
4.1.7 throws keyword
Example:
class ExceptionEx7
{
public static void main(String[] args)
{
Thread.sleep(10000);
System.out.println("Hello Geeks");
}
}
Output:
error: unreported exception InterruptedException; must be caught or declared
to be thrown
Explanation: In the above program, we are getting compile time error because
there is a chance of exception if the main thread is going to sleep, other
threads get the chance to execute main() method which will cause
InterruptedException.
class ExceptionEx7
{
public static void main(String[] args) throws InterruptedException
{
Thread.sleep(10000);
System.out.println("Hello Geeks");
}
}
There are various built-in exceptions in java which can handle most common
exceptional situations. But there is a need to create our own exceptions for
handling exceptional situations specific to applications under development. This
facility is provided by java.
For doing so, we have to create a subclass of Exception class (Exception class
is already a subclass of Throwable class. The new subclass automatically
inherits all the methods of Throwable class such as fillInStackTrace( ),
getCause( ), getLocalizedMessage( ), getMessage( ), initCause( ). Apart from
this, we may also create new methods.
Once the exception subclass is created, we may throw this new exception ny
using keyword throw with following syntax.
Following example programs show how we can create our own exception and
throw it.
Example 1:
class MyException1 extends Exception
{
MyException1(String message)
{
super(message);
}
}
class UserDefined1
{
public static void main(String args[ ])
{
try
{
throw new MyException1("This is user-defined exception");
}
catch(MyException1 e)
{
System.out.println("Caught Exception");
System.out.println(e.getMessage( ));
}
}
}
Example 2:
import java.io.*;
class MyException2 extends Exception
{
MyException2(String message)
{
super(message);
}
}
class UserDefined2
{
public static void main(String args[])throws IOException
{
String name="0125";
String pass="Bvjniot0125";
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter password: ");
String str= br.readLine( );
try
{
if(pass.equals(str))
{
System.out.println("Password is correct");
}
else
{
throw new MyException2("password is incorrect");
}
}
catch(MyException2 e)
{
System.out.println("Caught Exception");
System.out.println(e.getMessage( ));
}
}
}