Unit 3 Exception Handling AKP
Unit 3 Exception Handling AKP
In this chapter we will discuss exceptions in the object-oriented programming. We will learn
how to handle exceptions using the try-catch construct, how to pass them to the calling
methods and how to throw standard or our own exceptions using the throw construct. We will
give various examples for using exceptions. We will look at the types of exceptions.
Exception is an abnormal condition or run time error that arises in the program during
execution. When such a condition arises in the program, an appropriate code is written so
that it can be handled.
A catch statement involves declaring the type of exception you are trying to catch. If
an exception occurs in protected code, the catch block (or blocks) that follow the try is
checked.
The below example is for division of two number if the value of n2 is zero
then program will generated arithmetic exception and the output will display “You
cannot divide a number by zero”.
Example 1:
class pb1
{
public static void main(String args[])
{
The previous statements demonstrate three catch blocks, but you can have any number of
them after a single try. If an exception occurs in the protected code, the exception is thrown
to the first catch block in the list. If the data type of the exception thrown matches
ExceptionType1, it gets caught there. If not, the exception passes down to the second catch
statement. This continues until the exception either is caught or falls through all catches, in
which case the current method stops execution and the exception is thrown down to the
previous method on the call stack.
Example 2:
class pb1
{
public static void main(String args[])
{
try
{
int n1,n2;
n1=Integer.parseInt(args[0]);
n2=Integer.parseInt(args[1]);
System.out.println("Div result="+n1/n2);
}
catch(ArithmeticException e)
{
System.out.println("You cannot divide a number by zero");
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("Please Enter two numbers");
}
catch(NumberFormatException e)
{
System.out.println("NumberFormatException generated");
}
}
}
Output 1:
Please Enter two numbers
Output 2:
NumberFormatException generated
Output:3:
You cannot divide a number by zero
try
{
statement 1;
statement 2;
}
catch(Exception e)
{
}
}
catch(Exception e)
{
}
....
Example 3:
class pb1
{
public static void main(String args[])
{
try
{
int n1,n2;
n1=Integer.parseInt(args[0]);
n2=Integer.parseInt(args[1]);
try
{
System.out.println("Div result="+n1/n2);
}
catch(ArithmeticException e)
{
System.out.println("You cannot divide a number by zero");
}
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("Please Enter two numbers");
}
}
}
Output 1:
You cannot divide a number by zero
Output 2:
Please Enter two numbers
Syntax:
try
{
//Protected code
}catch(ExceptionType1 e1)
{
//Catch block
}catch(ExceptionType2 e2)
{
//Catch block
}catch(ExceptionType3 e3)
{
//Catch block
}finally
{
//The finally block always executes.
}
Example 4:
class TestFinally
{
public static void main(String args[])
{
try
{
int data=25/0;
System.out.println(data);
}
catch(ArithmeticException e)
{
System.out.println(“You cannot divide a number by zero”);
}
finally
{
System.out.println("finally block is always executed");
}
System.out.println("rest of the code...");
}
}
Output:
You cannot divide a number by zero
finally block is always executed
rest of the code...
v. throws
If a method does not handle a checked exception, the method must declare it using
the throws keyword. The throws keyword appears at the end of a method's signature.
Example 5:
class test
{
void add()throws NumberFormatException , ArithmeticException
{
int a,b;
a=5;
b=0;
System.out.println("div="+ a/b );
}
}
class pb2
{
public static void main(String args[])
{
try{
test t1=new test();
t1.add();
}
catch(NumberFormatException e)
{
System.out.println("Incorrect number format is entered");
}
catch(ArithmeticException e)
{
System.out.println("you cannot divide number by 0");
}
}
}
Output:
vi. throw
You can throw an exception, either a newly instantiated one or an exception that you just
caught, by using the throw keyword. Try to understand the different in throws and throw
keywords.
By using throw keyword in java you cannot throw more than one exception but using throws
you can declare multiple exceptions.
Example 6 Write an application that generates custom exception if first argument from
command line argument is 0:
class Zero extends Exception
{
Zero()
{
System.out.println("Zero Exception Generated");
}
}
class pb3
{
public static void main(String args[])
{
System.out.println("***Exception Demo***");
try{
if (Integer.parseInt(args[0])==0)
throw new Zero();
}
catch(Zero z)
{
System.out.println("Please give some another number");
}
}
}
Output:
***Exception Demo***
Zero Exception Generated
Please give some another number
Example 7 Write an application that generates custom exception if any of its command line
arguments are negative:
class Negative extends Exception
{
Negative()
{
System.out.println("Negative Exception generated");
}
}
class pb4
{
public static void main(String args[])
{
System.out.println("****/////Negative Exception Demo///////******");
try{
for(int i=0;i<args.length;i++)
{
if(Integer.parseInt(args[i]) < 0)
{
throw new Negative();
}
}
}
catch(Negative n)
{
System.out.println("Any one or more of your command line args is negative");
}
}
Output 1:
****/////Negative Exception Demo///////******
Output 2:
****/////Negative Exception Demo///////******
Negative Exception generated
Any one or more of your command line args is negative
3) throw is use inside method body to invoke an exception and throws is used in method
declaration(signature).
4) By using throw keyword in java you can not throw more than one exception but using
throws you can declare multiple exceptions.
5) E.g
Throw
try {
Throw new ArithmaticException();
}
catch(ArithmeticException e)
{
System.out.println("You can't divide by zero");
}
Throws
void fun(int a,int b) throws ArithmeticException,NumerFormatException
{
int c;
try {
c=a/b;
}
catch(ArithmeticException e)
{
System.out.println("You can't divide by zero");
}
}
6.3 Difference between Checked and Unchecked Exceptions
Checked Exception:
The exceptions that are checked at compile time. If some code within a method
throws a checked exception, then the method must either handle the exception or it
must specify the exception using throws keyword.
Checked exceptions are checked at compile-time.
The classes which directly inherit Throwable class except RuntimeException and
Error are known as checked exceptions e.g. IOException, SQLException etc.
Unchecked Exception:
The exceptions that are not checked at compiled time. In C++, all exceptions are
unchecked, so it is not forced by the compiler to either handle or specify the
exception. It is up to the programmers to be civilized, and specify or catch the
exceptions.
The classes which inherit RuntimeException are known as unchecked exceptions e.g.
ArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException etc.
Unchecked exceptions are not checked at compile-time, but they are checked at
runtime.
Protected Visible to classes with in the package and the subclasses of other package.
private Visible with in the class. It is not accessible outside the class.
Private Y N N N
Default Y Y N N
Protected Y Y Y N
Public Y Y Y Y