0% found this document useful (0 votes)
7 views104 pages

week 5 java

This document is a lecture on advanced features of interfaces in Java, covering built-in interfaces such as Iterator, Cloneable, Serializable, and Comparable. It explains how these interfaces function, their methods, and how to implement them in classes, along with rules and best practices for defining and using interfaces. The lecture also touches on nested interfaces and the significance of interfaces in achieving multiple inheritance and sharing constants across classes.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views104 pages

week 5 java

This document is a lecture on advanced features of interfaces in Java, covering built-in interfaces such as Iterator, Cloneable, Serializable, and Comparable. It explains how these interfaces function, their methods, and how to implement them in classes, along with rules and best practices for defining and using interfaces. The lecture also touches on nested interfaces and the significance of interfaces in achieving multiple inheritance and sharing constants across classes.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 104

Programming in Java

Prof. Debasis Samanta


Department of Computer Science and Engineering
Indian Institute of Technology, Kharagpur

Lecture – 21
Interface -II

So, this is the second part of our discussion on interface, in the last module we have
discussed the Interface and basically introduces the basic concepts that is there in
interface in Java. So, today we will discuss some more advanced features are there in the
interface and finally, we will summarize the lessons that we have learnt so far the
interface is concerned. So, there are like different classes built in classes. So, there are
also some standard interfaces available in Java.

(Refer Slide Time: 00:52)

So, the there are few of course not many. So, the important the mostly used interfaces
those are already defined they are called the built in interfaces like here, Iterator,
Cloneable, Serializable, Comparable, these are the most frequently interfaces. So, in our
subsequent few slides we will go through each interface quickly and then understand
what they can do for us.
(Refer Slide Time: 01:23)

So, let us have the discussion on Iterator. So, Iterator interface is basically if there is a
collection of objects right and then how these collection of objects can be processed. So,
regarding these things the Iterator interface which has been defined in java dot util
package. So, in the java dot util package this interface basically help us to manage the set
of objects we can say the collection of objects.

Here the interface the name is Iterator as we see here this is the name of the Interface
Iterator which has few methods as we see here has next the next and the remove. So,
there the 3 standard methods are there in Iterator and you can use this interface to
implement our own class here is an example for example, how these interface can be
used in implement our own class. Here we can create we can just implement using the
concept this is the class this may be say example Iterator implements Iterator and then
here myShapes is the shape of some objects that you want to have it in the shape
geometry and then this is the Iterator iter object is created.

Now here if you see for this Iterator, Iter dot hasNext; that means, it will automatically
check the shapes the collection of objects and then it will check that whether the next in
the list of collection the element is there or not. So, here hasNext is basically the method
that is there in the interface is basically implements it and then this is the implementation
how it will work there. So, hasNext next similarly remove is basically another interface
to remove an object from a collection. So, this is the one example of Iterator interface
that is there in java more specifically in java.util package.

(Refer Slide Time: 03:27)

Now, Cloneable is another interface is basically this interface is basically to implement a


class which can create a copy of an object. So, it is a Cloneable means it will basically
make a copy of the objects, as you see here this interface. In fact, is a new application it
does not have any method it is basically empty and it basically helps us to have the copy
of an objects their copy maybe 2 types; one shallow copy and deep copy. If the shallow
copy it will just logically make a copy and the deep copy means physically make a copy;
that means, for all objects reference variables, class variables, instance variable,
everything they will make a separate instances or copy of the same object. So, 2 objects
will be created having the same things are there.

In some situations the duplicate (Refer Time: 04:26) of the objects needs to be controlled
and so, Cloneable interface can be called for this purpose and in case suppose this
interface does not work it throws exception. So, this exception regarding we will learn
about it. So, anyway if there is any mistake regarding the copying an objects, sometimes
there may not be any permission or copy is not successful, whatever it is there in that
case it will throw an exception which is for the preparing the robust program actually.
So, this is the Cloneable interface and then example here.
(Refer Slide Time: 05:05)

We can consider one example here this example is basically show how the Cloneable
interface can be used here.

Say for example, here basically the Car is a class which implements the Cloneable these
are the methods in this class Car and then here you can see these objects we create a
objects of type and then clone is the method that we have discussed here and this method
is basically make a copy, explicitly that is mean by the class declaration by the user. So,
this is the one example how the Cloneable interface can be used in Java class declaration.

(Refer Slide Time: 05:44)


And the next is Serializable interface, this interface is basically helps a programmer to
build their classes while they want to communicate or send some objects over a network
to a distance objects or distant pc distant server whatever it is there.

So, this basically helps to make the things called the Serializable and here is a quick
example of the Serializable in again from the Car is the class support it implements serial
Serializable interface whatever the methods we have discussed in the next class we can
copy it verbatim here. So, this will complete the class declaration and here is an example
how the Serialization Serializable interface can be used in the machine. Here you can see
we create the object for writing or reading, from the writing from the network channel or
reading into the network channel or writing into some file or reading from the file.

So, these basically all the methods that we have discussed that is there as an abstract
method interface can be redefined here in the class declaration and can be used here. So,
this is an example of Serializable interface and then finally, the idea about the
Comparable interface.

(Refer Slide Time: 07: 08)

So, here is an example of Comparable means sometimes it is required to compare 2


objects whether they are same or different. So, if it is like this. So, Java developer has
proposed one interface called the Comparable interface and here is an example of this
compare interface and we see how it the method that is compared to which is basically
interface method we redefined here in our class declaration.
So, this is basically the user defined redeclaration for the interface method and it
basically compare objects. So obviously, it is up to the user for comparing the different
objects how you can compare one objects with other objects belong to the same class
whatever it is there. So, this will written Boolean values whether true or false like. So,
this is the interface Comparable that is defined in the again all these are also defined in
the java dot util dot package.

Now so, these are the few standard interface usually programmer prefer to have their
own interface related to the particular project and use them in their program, other than
using the standard interface those are there in the Java system. Now this basically covers
all the basic concepts about the interface and before concluding this interface concepts I
just want to highlights few more important things which is very important to remember
whenever you are handling with interface.

(Refer Slide Time: 08:45)

So, the defining an interface as you have learnt that an interface can be defined using the
special keyword that is there in the Java is called the interface. So, here basically the
basic syntax is the interface declaration by using the interface and giving the name of the
interface and then this is the body of the interface. Now, so far the body of the interface
is concerned this body includes few things.
(Refer Slide Time: 09:10)

The variables or members and the methods and as you have already mentioned that, the
methods which should be there in the interface should be declared as a public and
abstract there; that means, the method should have the only signature giving the name
return type then parameter list and no body of the method. On the other hand so far the
members are concerned the member should be declared as public, final, static and they
can be initialized by some values actually the methods the variables or members which
are there in a interface they should be treated as a global.

So, if any class which implements this interface has the complete access to all the
members that is there in the interface and the methods needs to redefine the class which
implements an interface. And as I already mentioned while I was discussing about the
interface that if you do not declare a method as abstract or is a fine abstract or public by
default it will be taken as a public and abstract and more one important concept is that no
methods should not be declared as a static. So, static method is not allowed in any
interface declaration. So, these are the few rule of thumbs that you should consider while
you are declaring your own interface in your program.
(Refer Slide Time: 10:42)

Now once the interface is defined this interface needs to be implemented. So, this
implementation is by virtue of declaring a class, here is an example how an interface can
be implemented. So, the basic rule is that an inter say this is the class name which
basically implements interface and here there are two things are optional extends clause
is optional and then also it can at one time interface two or more interfaces implements
two or more interfaces. So, this basic idea is that a class can inherit from the other class
that is why the extends clause will take care and at the same time it can implements one
or more interfaces so, this is the concept.

So, then now we have demonstration in our next module to discuss about how all those
things works together and as I mentioned there this class that we should have and that
class should be declared as a public there means be this should be public here for
example, declare as a default it is not allowed. So, you have to mention that this is the
public.

Now there are few cautions that needs to be taken care whenever we implement an
interface is that if an interface in if a class implements two or more interfaces which has
the same method and then that methods should be overridden by the class and it has only
one copy. Now, when we say that same method it means that the methods which are
declared as an abstract in the interface they have the same return type same method name
and same list of parameters.
If anyone is different the method should be treated as different and then different in
implementation in the class is required. So, this is the important thing that you should
consider and the methods which basically implemented in your class also that needs to
be declared as a public, because these methods should be accessible by anyone. So, no
private, no protected method as an implementation is allowed in the class
implementation. So, these are few thing that you should note while you are considering
the implementing interfaces.

(Refer Slide Time: 13:02)

Now, here is a quick example here you can see that how an interface can be implemented
by a class, in this case the name of the class is Client and here you see this is the
Callback method which is there in the interface and we implement this method as a
public. And while we implement at the assembly we have to consider the return type and
the list of parameter should match these which are there in your interface declaration,
otherwise this will treat as a completely new methods the methods of it is own in this
class itself, what I want to say here is that. In fact, we are to overwrite the methods,
which is declared as an abstract and public method in the interface declaration ok.
(Refer Slide Time: 13:57)

So, this is some standards procedure that needs to be follow while we are using the
implementation of an interface by a class. Now here is another example that we can say
again this is a class Client which implements the Callback, Callback is an interface here.
So, this is the method that we have declared in the interface and implemented here and at
the same time the class which implements an interface it may contains, it may contain, it
may include it is own method as well the methods that is overridden in the interface.

So, for example, here this is one method which is the own method in this class client;
that means, it just like an inheritance concept like. So, it is basically one other way you
can say that this class clients inherits the Callback where the Callback is an abstract class
we can say in that sense. So, this is the idea about how a class can implement this means
that implement means the methods should be overridden and it can include its own
methods if required and no variable should be declared with the same name as that is
there in the interface there. So, the method should be in fact, because it is a static and
public declared in the interface. So, we cannot redeclare or redefine the same variable
name or members in the class implementation ok.
(Refer Slide Time: 15:31)

So, this is the idea about some implementation of the interface by means of a class and
Java also allow partial implementation. Say suppose in an interface there are two
methods and you implement this interface by means of a class only one method, then this
class can be treated an abstract class; that means, no that means, that means, no objects
can be created for this class until you override all the methods which are there in the
interface. So, you have to override all the methods so, that you can create an object or
you can complete the implementation of an interface in a class.

(Refer Slide Time: 16:15)


And in Java also it is possible to allow nested interface, what is the meaning of nested
interface is that an interface can be declared inside a class declaration. This means that
this interface is a very much local to this class itself; that means, no one class outside this
in class is responsible for implementing this interface. This is the concept of it is called
the nested interface, this is a very restrictive use in the program usually we avoid it, but
sometimes we want to make an interface which is a very explicit to a particular class
only then we can think for this kind of implementation otherwise you can ignore it.
Anyway this is an example how the nested if is possible.

(Refer Slide Time: 17:10)

Now let us look at this small program here and this is the class A declaration as usual the
standard normal class and you can see within this normal class we declare an interface
this is the interface. So, we declare as an interface as NestedIf and the method in it is an
abstract method and then we can inside this class as you have the interface, interface
does not have any utilization until you implements it. So, here is the class B which
implements this is the NestedIf and you can see one thing that NestedIf we have
expansion A .(dot), there is a special location specification that A .(dot), means it is the
interface which is declaring the class A.

If you do not do in this case it will work, but in some situations if inside A class there
more than interface then better to do it like this one. So, otherwise if some interface
already in the same name appears somewhere else then it can give a what is called the
ambiguity. So, in order to resolve this we have to explicitly mention that this interface
belongs to which class. So, that is why the specific location mention that is A .NestedIf
means that this is a NestedIf inside the class A.

So, this way we can define it and then finally, we can implement the interface that is
there using the usual concept and then same can be used in your main class wherever you
want to use it. So, it is the basic idea about that it is just like a scope of this interface
which is a nested interface inside a class is basically the static scope and it can be
resolved seeing the program itself and is a local, local to this class itself.

(Refer Slide Time: 19:04)

Now, let us have a very simple example about, what is the utilization of an interface?
Why we go for an interface? What is the usage of the interface? It has 2 important
applications; one is that whenever you use an interface it will it may if it includes some
members which are declared as a final, static and then a final static public they can be
used as a global variable look like and this variable can be shared. So, it is just like a
library of different variables that can be shareable from one class to another class.

So, this is a one example and another example; obviously, the great example the most
significant example that we can inherit in a multiple sense as you know Java does not
support single inheritance, but in an indirect way Java also helps a programmer to have
the multiple inheritance implementation. These are the two main usage and one usage
also it is there runtime polymorphism; that means, that will be discussed while we will
go for demonstrating the application of interface in our next module. Now let us have the
first example that how a variable can be shared across the classes if they are maintained
in an interface.

This is an example for like. So, suppose we want in this example here we can say we
declare an interface the name of the interface as the shared constants and these are the
different values and by default they are public static automatically there. So, they are
public static int and these are the different value variables and the values are there. So,
these are the basically we can say this as they are basically static variable sort of things;
that means, they are global look like. So, they can be used one instances in everywhere
there. So, these are the global variable look like as you can see in a more simple way. So,
whenever we declared all these value were members in an interface they can be
considered as a global variable look like.

(Refer Slide Time: 21:25)

Now, once these methods are declared we can use them in a program. So, we can just
create a program look like. So, this is the one class the name of the class is implements.
This class is questions which implements shared constant and basically it uses all these
variable names as you can see here. Now here in this class we define one ask method
which has this kind of structure.

So, if you go through the program you will be able to understand what exactly the ask
question is there, it basically takes a random number and this random number is called
prob and depending on the value of the prob it basically return NO. YES, LATER,
SOON, all these methods are all these members are which is already declared in the
interface. So, this is the idea about a simple example of course, that all these methods as
they are they will be used here as if there is a global.

Now so, this is the way that an interface can be used in this case and here is the
complete program that you can see how this program can be used.

(Refer Slide Time: 22:28)

This is a simple example another class ask me which implements shared constant which
use the previous asked method and it has it is own body it is there and then this is the
main methods which basically utilization of all the method in the last slides the ask
method in this slides the answer method and it basically code this one. If you run this
program it will be an interesting output which will be discussed while I will go for the
demonstration in the next module ok.

So, these basically shows emphasized that if you declare an interface then all the
members those are there is basically will be used as a shared variable across the different
classes.
(Refer Slide Time: 23:13)

And interface can be extended we have already discussed about these that. So, an
interface truly works like a class as the class can extend another class so, an interface
also can extend another class. So, suppose here the interface A and interface B using the
same extends. So, we can extend the class; that means, in this interface all the method
that is there or all the members which are there in the interface will be also inherited in
this one. So, the basic concept is same as the class inheritance also applicable to the
inheritance.

So, again I want to repeat it that an interface in mostly can be treated as a class look like;
that means, whatever the procedure that we can follow for class it can be only the
exception is that for a class an object can be created; however, for an interface no object
can be created that is all.
(Refer Slide Time: 24:11)

So, this is the one idea where the interface can be extended and here is a complete idea is
that on the interface extended the inherited interface can be implemented by means of a
class. So, this is the one example that basically explains how the inherited interface can
be implements. So, both the superclass interface super interface as well as the derived
interface can be used for implementation by another class. And then the multiple
inheritance is the significant what is called the use of the inheritance concept here.

(Refer Slide Time: 24:46)


So, here is a example that multiple inheritance means one interface can extends two or
more interface, but it is not exactly the extent rather it is basically the implements
actually. So, if we can plan a class which implements two or more interface then we can
say that this class in fact, multiply inherits two interfaces. So, the concept is there and the
concept is there in the class itself the multiple inheritance can be realized.

(Refer Slide Time: 25:15)

Now here few things have to be more few things have to be carefully noted first of all the
class suppose implements 2 interface i1 and i2 and there is a method say m which is
declared in both the interfaces. Then in the implemented class which methods needs to
be implemented in this regard I want to say this way that if the 2 methods are same the 2
methods are same in the interface in the sense that they have the same return type and
then same list of arguments, having the same type then it basically absolute no problem
you have to override only once.

Otherwise, all the methods which are there we have to override in the implementation
class implementation of the interface. So, this way it basically multiple implements all
the interfaces they are by multiple inheritance it is like this one.
(Refer Slide Time: 26:23)

There is another also example where we can have the class extends one class and
implements another this is also one example of multiple inheritance in there. So, by class
extends for example, class B extends class A and implements interface i then it basically
is a multiple inheritance concept it is there; that means, it extends class B A means that B
will inherit all the methods and members those are accessible to the class A class B it is
there in addition to the interface methods and the interface variable also accessible to the
class there.

Now, again another important rule that if the two interface have the same variable
declaration then it will give a compilation error that you have to somehow take care
check that the two interface does not declare the same members variables in duplicate in
the two interfaces or more than interfaces which are basically in used in multiple
inheritance and multiple inheritance is not limited to only two interfaces any number of
interfaces can be considered. So, a class can implements two three or many interfaces at
the same time, but extends whenever it come into the picture it can extends only one
class that is the important what is called the things that you should note ok.
(Refer Slide Time: 27:47)

So, this is a concept that and if you want to specify explicitly some interface and then
again the super keyword can be used. So, here is an example for example, super method
name is basically in the InterfaceName we can discuss about if it inherits from others
name to resolve the ambiguity if any. So, the super concept it is basically same way it is
basically namespace collision resolution as well as the method resolution. So, this is the
same concept also extendable to the interface here.

(Refer Slide Time: 28:19)


Now, we have learned about the interface and then more on the interface will be
discussed while we will have a quick demo on the interface and we advise you to have
the good lessons in the interface demonstration.

Now, our next topic that we are going to cover is very important topic that this topic is
basically to address the questions that I have mentioned here. So, there definitely is a big
question that how a Java programmer a software programmer can develop the program
which is very much robust; that means, fault free tolerant program. And then there are
many errors and particularly it is the concern whenever the program size is increased
from lows low size low volume to high volume because as the code size will increase the
number of errors possibility will increase so, how to deal with this situation. So, all these
things will be discussed in our next discussion that discussion is called multiple is called
exception handling concept.

Thank you; thank you very much.


Programming in Java
Prof. Debasis Samanta
Department of Computer Science and Engineering
Indian Institute of Technology, Kharagpur

Lecture - 22
Demonstration – IX

So, we have learned about the interface in last two modules and this is a plan for this
module plans for an I mean quick a demonstration of the different concepts that we have
learned in our lecture session.

(Refer Slide Time: 00:36)

So, in today’s Demonstrations mainly we have planned that how a user can create an
interface and then maintain it in their package. An interface as we have discussed that it
follows certain specific properties so if all those properties are not satisfied then whether
the interface creation will be successful or not that we will learn it. And then interface is
mainly used for inheritance purpose more specifically it is a multiple inheritance. So,
single inheritance as a multiple inheritance using interface will be discussed. And
another great application of the interface is to provide a dynamic binding in the form of
runtime polymorphism so, that will be discussed.

And then we have also mentioned that the abstract class and the interface has many
similarities between the two. So, what is the difference between the two so, in our last
demo that we will try to clarify further.
(Refer Slide Time: 02:04)

So, let us have the demonstration fast this is regarding how we can create an interface.
So, these are the first program that you can think about how an interface can be created.
So, we have to first create a package where we have to store the interface. let us this is
the name of the package, my interface. We have created a subdirectory named my
interface whereas the interface will be stored there. So, let us go to the subdirectory of
my interface and as we see there is one program then you can just open the program.

(Refer Slide Time: 02:22)


So, this a program, yes. So, this is the one program that we have developed just this
program as you see the package statement includes that this my interface is the in the
package named my interface and then the name of the interface as we have mentioned
here with the keyword interface the name of the interface is an interface. And in this
interface, we include two elements an as a member type integer and then the method
display or we can type void.

And as we see the member elements that we have discussed here we do not have
mentioned explicitly, but as you know in case of the interface the member element
should be public, static, as well as final anyway. So, these are the default explicitly you
do not have to mention implicitly also if you do not mention anything in an interface if it
is declared they will be created as a public, final, static and the method as we have
mentioned here the method should be public and abstract. So, we have we do not have to
mention it explicitly again. If you do it very it is good if you do not do also the java
compile time compiler will take care of it.

So, this is the interface that we have created and we stored this interface in the package
my interface. Now, let us see the application of this interface in our program.

(Refer Slide Time: 03:56)

So, for this we can write one program here as we know an in interface can be used if you
want to use this interface then a class should implement it is. So, this is a first the class
declaration the name of the class is Demonstration underscore 91 implements the an
interface which is in the package my interface we have to input this of course. So, this is
the input statement as we see in the code at the top.

Now, so this method the method in this class demonstration as the implementation of
display because in the interface the method display is there. So, we just implement the
code the display here. So, the code includes a simple print statement, fine and as you do
not have to do anything the member element so no issue it is here and in this method the
main method as we see we create an object of the class Demonstration underscore 91 and
then we call the method display is basically interface method it is here.

And also in the last statement, you can note it is basically the print state statement in the
main method, but it can access the member elements which is already there in the
interface method a. So, this is the way this program compares with use and interface and
let us run this program.

(Refer Slide Time: 05:20)

Here, in this case, the main program is Demonstration underscore 91. So, if you run it,
so, if you run it we will see exactly how it works ok.
(Refer Slide Time: 05:42)

So, the program is compiled successfully. So, this program runs it, right. One thing you
can see whenever you create an interface a class file also should be stored there as you
see in my interface both the interface in the form of .java file as well as the .class file is
also stored there. So, it is the customers as we know the process of package creation both
.java file, as well as the class file, should be there.

Now, so in the interface, as you see that thus keywords public then final static void a
method is not necessary. So, if you put it that will work fine no problem, but if you do
not put it also it will work of it is own no problem. Now, our next demo let us have the
next demonstration after knowing how an interface can be created and then how the
same interface can be used in the program.

So, our next to the illustration that the whether we can create any object of the interface
type? Now, so, in this illustration will give you an idea about. Let us consider the
interface.
(Refer Slide Time: 07:03)

Let us consider an interface C here. So, this is the interface ok, built it here. It can be
stored in any subdirectory, in the same directory so, this is the interface. Now, our
objective is to if we attempt to create an object of this interface so, what will happen?
Now, let us see the program that we can write it a class program maybe and then we
want to create an object of this.

So, let us have the class program here. So, this is a class program the class file name of
the file is Demonstration underscore 92 and here you see the main method. The main
method is basically in the main method we try to create objects of the type interface there
are many ways we can create. So, in the first statement as we see the C is the interface
type and small c is an object name-new C. Here we want to create an object of the
interface C. As we told you as interfaces is an abstract so, no object can be created. So,
definitely, this will leads to an error.

And, then so, the last two statements you can make it comment ok. So, we will discuss
about the last one. Now, let us see if we do it whether we can do it or not.
(Refer Slide Time: 08:42)

Now, as you see here is a compilation error in the statement where we have attempted to
create an object of interface C so, it is not possible. So, now, let us again revise the
program so that we can comment on this statement and then now the other two statement
let us see. Now, the other two uncomment it so, other two statements uncomment,
nowhere again. So, here C is an interface type and it create an object c 2, this is quite ok.

Here basically we so, there is two difference between the first statement and the this
second statement. The second statement basically creates an object and instantiation by
calling the constructor, but here we just simply declare an object c 2 of C type. So, this is
quite possible we are declaring only, but not creating a new object, no instantiation is
involved. In our second case also we can declare an array of types C through an array of
the interface object, but not any instantiation. So, what we can say is that instantiation of
an interface type is not possible however, declaration of interface object is possible.

So, in that sense the last two statement is correct. Now, let us see if you run it. So, this
program run successfully this means that we can create it. Now, we will see the usage of
this kind of declaration in our next example we will discuss it, not now ok in due time.
(Refer Slide Time: 10:30)

So, now we have discussed about the interface; how a interface can be created and then
how the same interface can be used in our class program. Now, as you have told that an
interface should be implemented and in the process of implementing all the methods
which are there in an interface should be implemented successfully. If you do not
implement any method or if we implement one method as a private or something other
type then it should give an error.

So, now, let us have the complete program here. Here in this code we see the first few
declarations about Interface I1. In this interface, we declare one field called PI and
declared public static final that is ok. Also, we declare another member element lambda
the floating type. Now, so, this is fine and then also in this method in this interface we
declared on a public abstract method by default namely the void method 2; method I2
here ok.

So, all these things are perfectly it will work because is as per the specification of the
interface declaration. Now, as we know in the case of the interface only the member that
will be declared as a static no instance variable is not possible. Now, let us see if you
want to declare a variable say x of type integer and it is declared as 100 and so, these
basically considered as an instance variable. So, this leads to an error if we run this
program. Fine, we run it, later on, let us have a few more discussions about it here.
(Refer Slide Time: 12:12)

Now, here class A1; class A1 implements I1 and this is a simple implementation where
we have the class A itself its own member A1 and then method 1 it's own and then
method 2 is an implementation of the interface method. And as you see as the class A
implements I1 all the elements those are there in an interface are readily accessible to
this class A. For example, PI this is accessible via the method of its own method I1. And
now the main class as we see in the main class here we just create an object of class A1
and then all the methods which basically implements the A1 including the class A1 own
method is invoked here.

So, this will run successfully, but before running this program that definitely we should
comment the int x. comment int x should be commented here no next one, now fine. So,
this program compilable, as well as executable so, let us quickly compile it and then we
will come back to this program.
(Refer Slide Time: 13:25)

Again making the x as an instance variable and then see whether it work or not. So,
compilation is successful, no error has been reported and then this is the execution of the
program. So, it basically calls method I1 and method I2 from the program itself. As you
see method I1 can access the pi which is defined in the interface now let us come back to
the program again and here we are in the process of creating the instance variable here.

So, in int right now. So, here int x equals to 100 as we know that this is basically if you
do not specify the keyword that is basically public what is called the public static will be
default there. What about the int x declaration so, this comment keep it here no problem.
this one. Now, let us see that is what this basically creates an instance variable basically
run compile.
(Refer Slide Time: 14:46)

Now, here we can see int x without any initialization it indicates that it is basically as it
works as an instance variable. So, if we declare without any public static final keyword it
will automatically specify this one but this is only applicable after the initialization. You
should if it is a static variable you should initialize this one. As there is no initialization it
is as an instance variable and no instance variable declaration is allowed in an interface
method. So, this example explains that we cannot declare any instance variable this one.

Now, here so, we have learned about that a class can implement an interesting and
interface. Now, it is interesting to note whether an interface can implement another
interface or not.
(Refer Slide Time: 15:38)

So, here is an example as we see here I1 is an interface declared with its own member I
as 555 and its own public abstract method namely print interface and here is a second is
there I2 interface basically attempts to implements I1. In fact, all the entire course is
invalid code because I interface I2 cannot implement another interface. Now, if we run
this program then it will report a compilation error.

As you see in the statement interface I2 implements I1 it basically is an error indicated


here. So, instead of interface I2 if we write class I2 implements I1 it will work possibly
and another thing is that in the last statement print interface if we made it we have to
make all the method that needs to be implemented as a public. Suppose if we declare as
default the print interface method in class I2 yes, just write public term remove ok, fine.
So, here it is a default.

Now, let us see no default method implementation is allowed or method implementation


with any other access specifier is not allowed. As we see here in the void interface it
gives an error so, we have to make it public there then only it will be there. Now, a class
can implement another interface if a class implements any methods which are there in an
interface that methods should be declared as a public that we have learned it here ok,
right. So, we can run it.
(Refer Slide Time: 17:52)

Our next example, whether an interface implements an abstract class? As we know an


abstract class in many ways similar to instant interface that abstract class also can have
the abstract method that means method without any code and then it also can include the
static variable. So, here you can see in this example a class C is an abstract class as we
have declared and here the static variable is declared as a and it has one method print, but
in case of abstract class we know it can include both abstract method as well as non-
abstract method; in this case it is non-abstract method.

Now, if I if we attempt to implement interface this class C that abstract class by using
implements it is basically invalid. Now, if we run this then you will see this program will
not compilable actually. It will give the compilation error as we see interface I2
implement C is basically it is not allowable to implement this one ok. So, no abstract
class also can be implementable using any interface, but a class can be a plan to
implement this one.
(Refer Slide Time: 19:19)

Now, one thing is that no method or any variable can be declared final in case of
interface it will lead to an error. Here is an example. Here we can see interface I1 which
has one static variable public final it equals to 55 by default it is final and now, the
method here we can declare you can see we have declared the method as a final and
static. Note, these two keywords are not applicable to any method declaration in an
interface only public and abstract is applicable. So, by default it is abstract so, final static
is not possible. So, this code will work only if we remove the final and static from this
one.

Now, let us have the final static and learn it and one by one if you execute it will see it in
the next code basically class C implements I1 it basically declares its own method public
and then implements the print interface here. As you see there is an error so, the error is
the modifier final not allowed here. Now, let us remove this modifier final and run it
again keep it static ok. Now, run it again and let us see whether a static keyword is not
there. Here we can see it also reports an error missing method body or declares abstract.
As you have declare the abstract it is not taking this one. So, if we remove this static
again it will now final, public it is basically, abstract we can write it or not write now it
will work. So, void printed you have to declare public so, that is fine.

So, declare the public in the class implementation as we have not declared the public all
the implementation of the interface method should be declared as public here ok. So, fine
now this program runs successfully. So, there is a mistake regarding the name of the
class file. So, that is why it gives an error that it did not find the class file. Now, we have
changed it, yes ok. We are compiling; yes, the compilation is success full in this case
running this program anyway.

So, our next illustration anyway. So, the last illustration is not meant for any what is
called a class there, only for the explanation that it will require the few properties to be
satisfied.

(Refer Slide Time: 22:43)

Anyway, so, our next example basically explains the single inheritance. Now, here let us
have the loop of the code interface I1 with it is public static final variable x and then it is
method 1 and this interface I2 extends I1. So, an interface can be extended from I1, but
cannot implements. Now so, extend means I2 inherits I1 and so, as a process of
inheritance so, it has its own members y and its own method which is also abstract is
declared because it is an interface method. Now, class A1 implements I2 so, whenever I2
comes to this picture. So, by virtual of inheritance all the way method that is there I1
method 1 also now inherited to I2. So, here again, see in this class A1 implements I2
method as we see we declare one variable on its own. This is the class A1 variable and it
implements method one which is basically inherited from I1 via I2 and then also method
1 and method 2.
And, as you see here x and y are the two members who belong to the interface I1 and I2
and by the process of implementation class A1 has the readily accessible to these values
x and y here.

(Refer Slide Time: 24:18)

So, the main program looks like here we create an object of class A 1 and then we call
the method, method 1 and method 2. So, if we call so, all the methods and then they are
variables those are there in the interface will be readily accessible to this one. So, let us
have a quick execution of this program followed by the compilation.

So, we can see yes, we can see that this program is now successfully executed and
compilation there is no error there. Now, so, this is the idea about single inheritance;
now, let us have the demonstration on multiple inheritances.
(Refer Slide Time: 24:56)

Here again, I1 is an interface as we declare one of the static variable I here and print run
method in interface I2 is an again with there is again j as a static variable and print I2
methods are there. Now, multiple inheritance here as we see class A implements I1 and
I2. So, this is basically the idea about how to multiply a class that can inherit both from
I1 and I2. In the last example, we see that I2 inherits I1 then class implements I2. Here
basically class A can implements I1 and I2 here I2 is not necessarily inherited from I1 it
basically.

So, here as the number of inheritance can be implemented by a single class; for example,
class A implements I1, I2 and I3 and so, on we can write this one. Now, in this class
implementation as we see A value is the value of the class variable A and then print 1 is
an implementation of class interface I1 print I2 is an implementation of interface method
I2 and finally, the print A is a class A methods who basically have the full access of the
static variable those are there in interfaces i and j namely.

So, this is the program as we can see the multiple inheritances by the process of multiple
inheritances we can access all methods that are there in an interface as well as all
variables those are there in the interfaces ok. As we see this program run successfully,
now there is an alternative way of doing multiple inheritances our next demonstration is
to explain this one.
(Refer Slide Time: 26:47)

In the last example as we see class A 1 implements I1 and I2. Now, both extends and
implements can be added there; this is also one way of inheritance multiple inheritances.
In this example as we see class A is a class and interface I is an interface and will see is
the class B extends class A; that means, it inherits the superclass A as well as implements
I it is also inherited basically the some variable as well as method.

However, this implementation as it is class B should implements I the method print


should be defined here in this class as we have seen the public void where is a print
interface method. So, as we see interface I the print interface method is being
implemented here that print and then call it here and class B basically ok. So, it
implements the print interface method in an interface and then print B is basically its
own constructor who is basically called the class A constructor; that means, superclass
constructor using the super keyword and then also call print interface methods because,
this constructor has the access of because of the implementation. And the main class is
very simple here. The demonstration underscore 99 is the implementation of this where
we can create an object of class B and then we can call the print B the method of class B.

So, this is the one example as we see the multiple inheritances by means of extending I
mean inheriting a superclass as well as implementing an interface. Now, there are other
cases where it can extend on class A implements two or more interfaces at the same time.
(Refer Slide Time: 28:48)

So, this example is here class A is a class interface C and D are the two interfaces and
you see is a multiple inheritance form where class B extends A, that means A is the
superclass, class B derived from A as well as is implement C and D that mean class B
also inherits from C and D. That means, that all the static variable those are there in C
and D namely j and k is also accessible as well as the variable which is protected in class
is also accessible. So, we can see this method that is there or this class or main method
we can say can access all the elements by means of this multiple inheritance. So, this is a
one simple main method as we see here we create an object B which is basically derived
based on the multiple inheritance and then call the method print B ok.

So, this is the different way that we can see that how multiple inheritance is possible with
the help of interface as well as class A. Now, what is the usage of this interface we can
do the multiple inheritance, this is the one application. Our next example basically
explains our next example explain that the usage of the interface; in fact, an interface can
help to support the shared variable to use across the many packs’ many packages or
many classes in different packages.
(Refer Slide Time: 30:38)

So, here is an example as you see the interface includes declarations of some variable go
to the interface in the package my interface go to the my interface. So, we have declared
one interface here. This interface includes some static variable which is declared here;
NO, YES, MAYBE this one. Now, so once this interface is declared and then stored in
the package, then any other class can use them as a global variable look like so; that
means, it is called as shared variable in that sense.

(Refer Slide Time: 31:10)


Now, here is an example of one class which uses basically interface; that means the class
question implements all this shared constant to the basic global variable we can say. And
in this case is basically you see without any declaration it basically used return YES,
return LATER, return SOON all these things and here is a simple code we can use the
random function which is defined in java.util it will basically generate a random number
and based on the random number generation it will print all these values depending on
the random probabilities.

(Refer Slide Time: 31:34)

Now, here this is another class that basically uses the same things here and we define
another method called answer and it basically take the results first do it and based on the
result it will execute this codes are there. Now, let us have a quick method. In this class
is as we see go to the next, so this method basically creates an object of question class
which is declared which use the interface or implements the interface.

And then for this class, we use the ask method. Ask method generate a random number
based on the random number it will print either YES, No, SOON, NEVER, maybe all
like this one. If we run this program let us see what is the output it will give. It will give
the output as it is a probabilistic one. So, different execution will keep you not
necessarily give the same output in this case ok. In this case, we can see this is the
output. If we run the same program again we may see different output like this one if we
run again it can give another output and so on.
So, it is basically a probabilistic program by means of generating a random number, but
it will be discussing about how the shared variable can be used across the different
classes. Now, we have to discuss in the ok, what is the difference between interface
object and then abstract class interface type and then abstract class declaration.

(Refer Slide Time: 33:09)

Now, we have let us have the one program here and it is a basic idea about the
inheritance and by means of inheritance we can create many objects there and let us go
to the main class ok. First, discuss about the interface class here. Interface class goes to
the interface class interface go to the interface, fine no not this is the interface right ok.
(Refer Slide Time: 33:44)

So, now, this interface is defined in my package in the package myInterface. The name
of the interface is GeoAnalyzer as you see this geo-interface geo analyzer interface has
one static variable namely pi and then two public abstract method areas and perimeter.
So, this method is basically the type and now we want to create few classes which
implement GeoAnalyzer namely circle, ellipse and rectangle. So, this is the
implementation of circle class which implements GeoAnalyzer; this is the
implementation of the ellipses class which is an implementation of GeoAnalyzer and
GeoAnalyzer this is the implementation of rectangle class which is the implementation
of the GeoAnalyzer it has its own this one and this one ok.

So, now, we see the different class implements the GeoAnalyzer interface by the
different methods actually in their own way; circle has its own implementation, ellipse
has its own implementation, rectangle has its own implementation. Once this
implementation is done now we can come to the main program which basically create
the objects of this.

Now, here we can see the demonstration 912 is the main class and there is basically the
method includes a display which basically take x and y, namely the area and perimeter of
the geo objects. And here we can see we have created three objects; one object c of type
class c, another object e of class Ellipse and another object r of class Rectangle.
Now, here Geoanalyzer geo-Item the interface and geo-Item is an object of interface we
can just declare. So, we have declared and then once it is declared we see it basically
holds the class c, basically the upcasting c is equal to geo item. Now, if we do this then
we can call the display method which is defined in the main method by calling this geo-
Item.area and geoItem.perimeter. Similarly, if the geoItem holds the reference to the
ellipse object, then also same method can print it. But, in this case, this geo the display
geoItem area for the referencing of ellipse object call the method area which is declared
in ellipse class.

And, then again if it refers to rectangle and then displays area of this one, it also refers to
the methods that are there in an interface rectangle in the class rectangle. Now, here we
can see the display method is basically binded polymorphism. The different the display
methods can display area, perimeter for the different objects as per the references there.
So, it is a great example of polymorphism by means of interface.

Now, this program if we run it will work for us, now again repeat the same thing, but
using the abstract class. So, in the previous case, we have discussed about Geoanalyzer
as an interface we just want to do the same thing by means of abstract.

(Refer Slide Time: 37:08)

Here is basically this abstract class is declared in a package let us have the package it is
there ok. So, this abstract class is declared here go to the abstract class their geo
geometry. So, here we can see public abstract class geometry is an abstract class here and
here we define two methods and abstract method abstract as you know the abstract
method means no code is there just look like a very similar to an interface.

Now, this basically example to illustrate the similarity and dissimilarity between
interface and abstract it is there. Now, let us have the second same way of class
implementation it is basically extended because circle should extends geometry here we
can see circle. Now, the difference we can note in the previous case circle implements
Geoanalyzer, but here geometry being an abstract class we cannot implement, we just
simply circle extends geometry. Likewise, Ellipse extends geometry and then Rectangle
extends geometry as a process of extension is basically single inheritance as you know.

So, it basically inheritance or you can say override the method those are there in abstract
method incase of geometry. So, these are the three implementations of three classes
extending the geometry object and finally, the main class here demonstration underscore
9.13 so, this is the main class.

(Refer Slide Time: 38:35)

As you see the main class here it is more or less similar to the previous example user
interface. Geometry we create we basically declare an array of what is called the objects
of geoObjects of type here three array size is three here arrays of the abstract class
method we can say just the interface objects we have created in case of interface in case
of abstract class also the object can be created as we see here. And, then geoObject 0 we
create an instance of the class circle and then it is basically assigned to the location 0 and
similarly a rectangle instance and ellipse instance are created and we call the we pass the
parameter to I mean instance share them properly.

So, these are the instantiation and instantiation, but after the instantiation they are
basically referred in the abstract class object like geoObject in this case and here again
runtime polymorphism as we see in the next for a loop. So, here total area geoObjects
i.area. Now, for i equal to 0 so, this will this .area refers to circle objects on the other
hand for i equal to 1, this area refers to the Rectangle objects and then for i equal to 2 this
area refers to Ellipse object. So, again it is an example of runtime polymorphism.
Because it is polymorphically resolved that different method depending on the objects it
is there although it looks like same for all calls actually and if you run it the similar to the
interface it will run and then give the execution ok.

So, this is the right. So, this is the successful execution of the program. So, what we have
learned about here that more or less interface and abstract behaves in the same manner,
then why java developer maintains both the thing? The difference only here is that
abstract class if you declare it cannot be multiple inheritance or whenever an inheritance
interface is there it can be multiple inheritance. So, this is the only difference between
the abstract class and the interface otherwise both the concepts are more or less same.

So, we have learned about the interface and if you have further any doubt you are most
welcome to post your queries and all the programs that we have used in their
demonstrations you are free to use it and then test it so that you can practice it much
more.

So, thank you very much.


Programming in Java
Prof. Debasis Samanta
Department of Computer Science and Engineering
Indian Institute of Technology, Kharagpur

Lecture – 23
Exception Handling - I

So, let us start this lesson with a question. So, suppose what is the big headache for a
programmer, whenever the programmer has to develop a very large and complex
software. So, many questions may come whether we have to design it properly or the
coding should be done by an expert programmer or there should be adequate testing
while this one.

In fact, all three things are very much essential, and in fact is a concern for any software
development team. Now, java is famous and java is basically at the top, because at the
time of coding the programmer can introduce some things into the program itself, so that
the program is fault free, error free, and then robust program development is possible.

Now, this is possible in java using a concept, and very useful one concept which is
basically unique of its kind, and then java only the java language provides its other
programming language C++ in some extent it provides, but it is a very unique, and new
of its kind in java, the concept is called exception handling. Now, exception handling
coming into the way to dealing with errors in the program. Now, before going to have
the discussion on exception handling, we should understand about what it does mean
about errors in a program.
(Refer Slide Time: 01:53)

Now, so for the concept of error is concerned, there are two types of error in java
programs. One is called the compile time errors, and another is called the run-time errors.
So, the compile time errors is very easy, because it is not your headache to debug it.

If you write some program which is not seen practically correct that is not written
according to the language specification, then it will report an error. And this report, this
error will be reported by the compiler java compiler java, C program itself. So, this is the
compile time error. And there are many situations in the compile-time error is concerned.

But, I am not so much concerned about compile time error, because if you write a
program according to a right syntax of the java programming language, then compilation
error is no more there. But, if you have suppose some mistake programming mistake
right, then compilation compiler will report an error, and you can fix the error, and then
you can develop the program you I mean successfully compile. Once the successfully
compiled a program, there will be compile-time error, error free compilation, compiler
free program.

On the other hand which is more concern more headache, this is called a run-time error.
This is very difficult, because java program is written successful is compilation is
successful, but while it is running the program that time, it does not give the correct
output or its abrupt termination or there maybe some causes with damage some files
stored in a database or like this there are. So, these are the errors is very critical.
And if we do not take care in a very sincere manner, when it leads to a many (Refer
Time: 03:38) there. So, many loss in many resources concern is due to this run-time
error, so that is why java run-time error needs to be checked, needs to be controlled,
needs to be maintained manipulated properly. So, this lesson is basically dealing with
this one.

(Refer Slide Time: 03:55)

Now, let us have an idea about what is the compile time error, and what is the run-time
error. If we see this program, could you check the program, and tell me what are the
possible points or locations there, it gives the compile time error ok. If I can help you,
you can see I am pointing out. So, there is a location of the error, and here is an error,
and here is the error, and here is the error. You can understand why there are the so many
errors are there. These are the errors, because according to the java syntax it is not
written.

On the other hand if we see other program, may that we cannot find any errors here, this
is correct in all sense; maybe that this is an error, because in this class a public is not
accessible, whatever it is there. And so this is the idea here and this is also we can find
one error, you can tell me why this error, because you have declared a method is abstract.
Whenever we declare an abstract, no code should be included here. So, there are few
errors these are called compile-time errors.
So, when you try to compile this program, java will specifically state in this line number
this error, in this line number this error, in this line number is this what about the things
are there, in report the line numbers. And for each line numbers, whatever the
compilation errors are detected will be reported to the programmer, so that programmer
can correct it, and then right and then syntax syntactically correct program can be
written. So, this is the idea about compile-time errors.

(Refer Slide Time: 05:35)

Now, let us come to the example of there are many situations, when the compile time
errors are there. From the last example, you can understand that. There are so many only
few of course; there are many reasons where the compile-time errors are there.

In fact, a java program when starts is programming right programming have it is then
usually at the very beginning he faced many errors compiled time errors. And whenever
he become experienced, and then from beginners to little bit advance then next part, then
he will be quickly able to see that this is a compile time error. Usually, do not face
compile-time errors actually in the program.
(Refer Slide Time: 06:17)

Now, so this is the compile time error, and then what is the run-time error let us have a
look. Now, this is the one program we can see, and this basically if you see the program
and if you compile, it this will compile successfully, because there is no error in this
program; so, for the compilation is concerned.

But, whenever if you want at try to run this program, we will be able to see that all this
input will be taken this program successfully, there will be no error. So, there will be
run-time error. But, there may be run-time error, whenever we have to give some other
input in the same program.
(Refer Slide Time: 06:53)

For example, if we give this example this input, then you will see these program reports
an error. So, this is basically is a unknown format error because of this statements.
Because, this statement only take the integer; but you have passed as a floating point
number and that will not allow. So, this is basically run-time error.

So, what we can say is that so far the run-time error is concerned; the program can run
for some input. But, if it cannot run for all possible inputs, then it leads to run-time error.
So, when you write the program in this case for example, you have to define the program
in such a way that if it works for the integer type data only, then, you have to check it. If
it if a user gives other type of input, then accordingly it will it will check it and then
report it, so that that kind of input can be bypassed, and then program cannot terminated
abnormally. So, this is idea about run-time error is concerned again like compile time
error.
(Refer Slide Time: 08:05)

There are many sources many reasons that line run-time error will occur here. I have
mentioned only few some important things which usually occurs there, and there are
many more in fact. We will discussed in our while discussing about that robust java
program writing, then some errors will be discussed here. I have listed few errors, which
are usually common type of errors, but there may be many more errors are possible.

Now, so these are the basically run-time errors. Now, this is very difficult, because while
a program is writing that time program has to take care of all possible checks that this
one. But, sometimes it is very tedious, and obviously the programmers say ability that
programmer cannot do all kind of checking’s, so in that case what is the way out.
(Refer Slide Time: 08:57)

So, the as a way out java provides a mechanism call handling errors and exception in
Java program. So, it is basically the who will do it, definitely compiler not do, compiler
only check the syntactical error, which reports as a compile time error. But, this is the
error and exception which basically occurs; I should not say exception at this stage,
because I have not discussed any exception here. I can tell only error. This is checked by
java run-time interpreter environment is our java run-time system.

Now, java run-time system whenever find an error is basically in order in leave of
abnormally terminating the program, then it basically throw an exception, and the java
programmer should have the facility to catch the next session, so that (Refer Time:
09:55) bypass this error. And then for the rest of the part, it can be executed successfully,
if they are correct. So, this is a concept.

So, whenever there is an error or some abnormal things is occurred, java run-time
environment will catch it, and then throw it, and then java programmer will process it, so
that abnormal termination can be avoided. Now, here is an example suppose here is a
method suppose you have declared as integer X and Y, and in some program by mistake
user called this as a this one 1.5, 4 and right. So, compilation error will not be reported
here. But, at the time of execution whenever input is 1.5, it will throw an exception, so
that this method cannot be invoked, and then by pass.
As an another example here you can see, whenever we have to perform an arithmetic
operation like this one, and if suppose b and c these are the two variables values is equal,
then it basically gives rise to an error, it is called the divide by zero error. And if you
show in C programming, if there is a divide by zero error, then the programming (Refer
Time: 11:10) without giving any in output for the rest of the programs or whatever it is
there.

But, in case of java if we can catch this one or in this kind of error occur for this kind of
situation, then java run-time environment will throw an exception. And then with the
catching this exception, we can take care about this kind of errors in the program. So,
this is the concept that error and exceptions in java can be handled during the run-time
and then, avoid the errors.

(Refer Slide Time: 11:41)

Now, so for the errors and exceptions is concerned in java program, there is a big what is
called the development. And there in java, there is a package called the java.lang
package, which basically discussed many classes. And here is a class hierarchy as we see
there is a class called Throwable.

And this throw able can throw two type of classes called error and exceptions. And for
the exception there is IO exception and then run-time exception. So, this is a total class
hierarchy or the mechanism dealing with error and exception in java program. So, this is
a concept called n exception handling in java. So, there is a class as I told you java.lang
package, which basically define all the classes it is there.

(Refer Slide Time: 12:43)

Now, let us see about little bit details about the different possibilities about the class and
then exception handling mechanisms that is there it is very big story. So, we will cover
this kind of discussion not in one module, we may take two more modules to complete
the discussion with illustration. And then finally, we have a demonstration; so that we
can pin point exactly how the things the mechanism works for us.

Now, first let us have the idea about in general what is the exception handling
mechanism it is. As I already mentioned about that java provides run-time error
management on concept. In fact, java this is the error management, there is memory
management, and there is synchronization management, there are many other
management schemes are implemented there.

So, java run-time error management is a policy is a scheme which basically take care, if
there is any error occurs in the program. If there any occurs, if there is any error that that
may occur in a program, it can catch it, and then this can provide say solution to get the
premature exit of the program, therefore loss of other data or damaging of any system.

So, regarding these things in java or I can say the java exception mechanism handling
mechanism consist of five specific keywords. So, five keywords are called try, catch,
throw, throws, and finally. So, these are the keyword likes a class keyword, interface
keyword class, then extent keyword like this one these are the also keyword, we have to
embedded into the program.

(Refer Slide Time: 14:27)

Now, let us see how we can do all this things are there. In general, these are the
keywords that we have already mentioned here can be embedded in a program. So, for
example, so suppose you are declining method, these are beginning of the method, end of
the method.

And if we see this is the possible scope of error, so that obviously as a programmer
should know that there may be chance. For example, here and user should give an input
an integer, but sometimes user by mistake or whatever it is can give other type of integer.
So, we can have a check, so like this on. So, we can put all check.

Now, here is basically try we will take care. So, try can check that these are the possible
sources of error in a program. So, whatever the course those are basically under scanner,
they can be put into this block is called that try block. And then for many errors there are
many different type of exceptions occurs. So, for each errors and corresponding the
exception, we can plan the catch, so if it is a divide by zero error, if it is a null pointer
error, if it is out of bound error, whatever it is there for each error, we can mention the
catch that means, if an error occurs, this block will take care what to do. So, for each
error they are maybe one or more block, we can plan for it.
And these are the finally right, so it basically whatever it is error occurs or not, it will
execute this one so finally. So, this is the basic what is called a scheme. So, for the
handling exception is concerned in a java program. So, usually call try-catch mechanism
try catch.

Now, here also in addition to try-catch two more things is a throw, in other sense is
called the throws also there. So, throw can be put anywhere there that mean explicitly if
you have to throw an exception, as I told you implicitly means java run-time
management whenever fine and error, it will throw and exception. But, sometimes you
can the programmer can explicitly throw and exception, so these can be achieved by
means of throw keyword. So, this is the basically in brief the concept of exception
handling mechanism in java.

(Refer Slide Time: 16:57)

But, now it is very important to discuss about each the block one by one each concept
one by one, now we can structure this concept in here is a six different way that is the
exception handling can be done by using simple try-catch that means, only one try and
one catch. There may be also one try with multiple catch. So, so this is the simple try,
then try with multiple catch.

And then they are may be multiple exception, which can be caught by only one catch that
is also quite possible. And they are also possibility that whenever the exception occurs, it
should finally execute some code. So, there is a concept called finally. And throwing the
explicit exception so throws or throw in a block. And another is a nested try-catch; there
mean within the try-catch we can defined another try-catch, within the try-catch another.
So, nesting; so try-catch within try-catch. So, these are the different six different way of
handling exceptions in java will discuss all these cases one by one in our nah subsequent
slides.

(Refer Slide Time: 18:21)

Let us first discuss about simple try-catch block. Now, typically a simple try-catch block
looks likely which is shown here. So, this is the method that we are going to discuss
here. As you can note that usually LR occurs in a method. So, we are discussing in the
context of method only, so this is a method declaration.

Now, in this method the statement which is basically the critical statement. So, this
critical statement can be put under the try-catch that is ok. So, eventually in a very
default sense for every statement, we can write one try catch. Then obviously; but it is
very tedious and programs very bulky, looks very clumsy and it is not desirable. Only if
you see that this is a possible causes of error, then we can put that block that coat under
the try-catch.

Now, so this is the try block, we will contain this is the code (Refer Time: 19:22) to
cause and error. And then what that cause at the end of this try, we can put a catch. Now,
here the syntax you should see, try is the keyword. And beginning and ending that
basically called the try block. So, this basically whenever an exception occurs, this will
be basically check it, so that is if you do not put this one, if any exception occur, java
run-time manager will not be able to throw it I mean handle it, so that is why we should
put it explicitly there.

And then this is the catch like this try, it is a keyword catch. And it has also beginning
and ending that means, if an exception occurs, what are the next steps the program
should do? So, this basically includes the code, if an exception occurs. So, this is the idea
about the concept of simple try-catch block. Now, definitely it is if you have an example,
so the concept will be understood better.

(Refer Slide Time: 20:25)

Now, let us have a simple example to discuss it on. Now, here let us have a look about
the simple class it is there, we have defined one class the name of the class is called
divide zero. And here one function is declared any function, this has two arguments
integer x and integer y. And here is the code.

Now, and this is the main method it is declared there now ok. Now, you can see where is
the source of error, if you look at this program? Now, here you can see there is a source
of error why, because this method any function can be called for any integer values that
is ok, it will work for any integer values.

However, it will not work properly, if the second integer is zero. Because, if second
integer is zero, they are is basically divide by 0. And no processing unit can deal with the
divide by zero error in a program. So, whenever y equals to zero, then if we put all these
things under a try-catch. Then it will basically if that situation occurs that y zero, it will
throw an exception, and then following catch will catch it, and then do it whatever it is
there.

(Refer Slide Time: 21:47)

Now, see this program is therefore not a robust program. So, what is the weather this
program can be make robust. And here is the one possible input that it will work easily
always, but sometimes it may not work.

(Refer Slide Time: 21:53)


And here is basically is an attempt to make the program robust, how you have done it if
you see, this is the code which is basically very critical code, so we put this code in the
try-catch block. So, this is basically under try. And if you see, this is the catch is
basically what is basically tell that x y is bypassed, enter y as non-zero. So, you should
passed the input y as non-zero like. So, this basically may send a message or an output to
the use at if this kind of error occurs.

So, here if you see, this code will not execute always. Only if error occurs here, then only
it catch and then accordingly it will execute. So, this is the way that we can build the
program, so that it can in a robust way that means, it will take any input including zero
the second argument as an input also. So, this is the idea about making the program
robust is a very simple example here.

(Refer Slide Time: 22:59)

And here is another example as you can see here what you have done here is that we put
these things in a try-catch block, you know why you have done it. It definitely because
this code will again leads to divide by zero or occur for some input if b equals to c. So,
here after if in case suppose this error occurred for b equals to c is basically report that
this occur there, and then it basically bypassed and this. So, this is the idea about the try-
catch or I can say that simple try catch mechanism in java to handle the errors.
(Refer Slide Time: 23:45)

Now, here again let us have the look, this program looks very innocent apparently if you
see that there is no errors. Now, can you tell me what are the possible errors are there in
this code is basically command line input that means, here if you see args dot length ok.
Args dot length is basically if it basically say that number of inputs, when you have
passed as a common line ok.

Now, so here is a possibility that user can run this program without passing any input
that means, this value will be zero. Now, if this value is zero or others or it passes
suppose two value, but argument of this array is much more, then there may be what is
called the is called the outer bound error there.
(Refer Slide Time: 24:51)

So, this program if you run it for many inputs, you may check that this program may run
for some input, but not truly for all input is there. Here, is a some instances I have
mentioned here that, this program will work for this as an input, this as an input, but not
this, but not this, now you can understand why this program will fail to run for this kind
of input, but not this one.

Anyways, so as a exception handling mechanism it is our duty responsibility, so that all


the inputs if user gives, then this program still will work that means, for the correct input
it will definitely work correctly. But, for the wrong input passed to the program, it should
take care them and then report to the user accordingly. So, this is the concept of the try-
catch block in your java program. The simple try-catch block in the java program and
here is the ok.
(Refer Slide Time: 25:43)

So, earlier program was not robust, because we see we check that this program does not
work for all. And this is an atom, how we can make the program as a robust using try-
catch block here. So, it is basically try catch block to take the full (Refer Time: 26:04) of
the errors that may occur.

And whatever the input we have mentioned in the last execution, if we run this program
with all the input, we will see this program will run. It will not give any abnormal
termination of the program, and then we can say the program is robust. So, this is the
idea about handling exception in a java program. And as an example you can see this
program if you run, it will work for you correctly successfully.
(Refer Slide Time: 26:31)

So, this is a basic introduction about the exception handling. There are many more
features many more things to be learned in so for the exception handling is concerned.
So, basically the idea is that we have learn about try-catch, but there are few more
features basically there, which makes more effective way of writing the program. And
there are many more features, so for exception handling is concerned. So, all these things
will be discussed in our next module, and thank you for your attention.

Thank you very much.


Programming in Java
Prof. Debasis Samanta
Department of Computer Science and Engineering
Indian Institute of Technology, Kharagpur

Lecture – 24
Exception Handling - II

So, we are discussing about, Exceptional Handling in Java and in the last module, we
have discussed the try-catch mechanism. In addition to this try-catch mechanism; there
are many more features, so for the exception handling is concerned. So, today we will
discuss a few of them and then other features advanced features also there. So, those
things will be discussed in our next module. Now so, now we have discussed about try
and catch block and there is another, this is simply what is called the exception handling
mechanism. Now, apart from this simple there is also one more mechanism, it is called
try with multiple catch.

(Refer Slide Time: 01:10)

So, there are many features, try with multiple catch is the one. So, here the idea is
basically, the methods, where we are interested to maintain the exception handling. So,
suppose, this is the entire method and then, so try with multiple catch implies that there
is only one try block and there is many catch block. So, two or more catch blocks are
there then it is called the try with multiple catch.
Here, if the concept is that in the try block it will catch whatever the exception will
occur, so only one try. So, try block will responsible for two catch all the exceptions and
for each exception, we have to maintain the catch block. So, that the corresponding
exception, for a corresponding catch block, we will take care.

So, this is the concept. So, a try-catch block is basically to indicates that if there are
multiple errors or exceptions occurs in a program, they can be tried it with one try block
and they can be caught with multiple catch block.

(Refer Slide Time: 02:23)

Now, here is an example, very simple example to explain how the try with multiple catch
we will work. Now, let us look at this program. Now, we can see there are multiple
points, where the errors may occur, as you can see in this program. So, it is basically
considering the common line arguments. So, if the common line arguments are there. So,
it basically has the args length; that means it, how many inputs that user has passed
through the common line that will be stored here and after that we can see this is one
point, where there is a scope of error or exception.

Why? This is because if a user does not provide any input, in that case, i equals to 0 and
if i 0, then this is not a valid one. What is call the declaration, is called the null pointer
exception. Now, another here is also if you see, there is also one scope of error, if a user
does not pass any input then args 0 is also a null pointer and there is another also, you
can see here, at this point also one error.
So, if i equal to 0 so, it is basically the arithmetic exception namely, the divide by 0 error
and here also if you see there is a possibility of error, if the value of i is more than 2
because here i then an array is initialized with two elements. So, an array index is
varying from 0 and 1. So, size of the array is 2 and then here if I suppose 3 or more than
1; that means, 2 then it basically, gives an error.

It is called the array index out of bound error. So, as you see this program can run for
some input, but not necessarily it will run for all inputs. So, if the program does not take
care about all those exceptional inputs, then it is the exception and this way this program
is in fact not so robust.

(Refer Slide Time: 04:53)

So, there are few input as you can see, if you try this program with all these inputs you
can see these are the; so, this is the one exception occurs in this input, here also
exception occurs and here also the exception may occurs. So, there is a different
exception that may occur for the different input like this.
(Refer Slide Time: 05:20)

Now, so, as a way out of these things, so they are basically, as I have mentioned again,
let us specific as there is a one vulnerabilities, here is also errors may occur and there is
also error occurs. So, there are three points where the error occurs, so multiple errors,
multiple exceptions. So, here is the idea about how we can handle with a try with
multiple catch. So, idea is that we can include all the statement where an exception may
occur under the try block and for each exception, we can plan the catch block. So, here is
an idea about these things, which is the program has been rewritten with a try with
multiple catch. Now, let us look at this program little bit carefully, we will be able to see.

This is the program that where we have included try with multiple catch as you can see
here is that, this is a basic methods portion, where the exception may occur at this point.
This is the one point, this is the here and this is the these are the three points at the
exception that may occur and to catch this exception, we have mentioned one catch. This
catch is basically to handle the null pointer exception error mainly here and this catch is
basically to handle arithmetic exception error divide by 0 error here and this catch is
basically to handle the array index out of bound error here.

So, as you see for the different exceptions, we can plan the different catch block. Now,
this is; obviously, not possible with a simple try-catch block, because it will catch only
one exception, but there is a master exception we can consider. This is possible, but if
you want to pinpoint or more specific about what particular errors or exception occurs
then definitely we should think for try with multiple catch. Now, so this is the one
features.

We have learned about simple try, try and catch, then we have discussed about try with
multiple catch and also it is possible to catch by means of only single catch block, but the
multiple errors are there. That is what I just wanted to discuss about these things in a
different way, that we have discussed in the last. See, try with multiple catch by more
errors, in the last example that we have seen, but we have planned more catch block, but
here multiple errors, but single catch box. So, this is the one idea about so, here is one
concept, the concept is like this.

(Refer Slide Time: 08:06)

So, this is the method as where the exception may occur and then these are tried, here in
this part many errors may occur as in the last example that we have discussed, but there
is one catch that can handle, whatever the exception it is there.
(Refer Slide Time: 08:29)

Now, here is an example that we can see, this is a very nice example to explain this
concept very carefully. Now, here if you see so, this is the method, main method actually
here. Now, under this main method as you see there are many points of exceptions that
may leads. So, here is the one point of exception, because 0 equals to here divide by 0
error. Now, here also you can see as b is initialized is a null pointer and we want to have
access b 0, the zeroth element.

This is also an error and here also you see, here the array c is declared, which size 2 only,
but here we want to access the tenth element, which is also not possible. And, here also if
you see these a string and we want to find the character at ninth position, where is the
string; has maximum up to third location, index is 3. So, here the string index out of
bound, here the array index out of bound, here the null pointer assignment and here the
arithmetic exception. So, there are so many errors that may lead to whenever we want to
run this program.
(Refer Slide Time: 09:48)

So, this program, if we run then it will give always this error, because of static error that
is there. Now, let us see what we can do so that this program will be more robust, more
reliable.

(Refer Slide Time: 09:53)

So, this can be implemented with only one catch and then on try. So, an idea it is like
this, here you can see. So, this is basically, as you have mentioned the try block. So, that
whatever the error will occur, it will try to see whether if any exception error occurs or
not and then here we can see a single catch. Now, in this catch, if you see, we have
thrown an exception of the class exception. Now, in other examples; in the last example,
we have mentioned the exception of a particular class, say; a null pointer exception or
arithmetic exception or divide by 0 exception or like this ok.

So, here is basically, we will catch-all. This is basically the super exception class. So, it
will catch any sort of exception whatever it is there, but if we write the catch, which says
array index out of bound exception e, then only that kind of exception that this catch box
will handle. But here the single catch will catch any kind of exception that may occur.
So, it is a general, general one implementation and here also you can see for the different
exception, the different messages meant already in the exception class, it is there.

So, this basically will print e.get message; that means, it will tell that ok. It is array index
out of bound exception or what type of exception it is there. So, this is the idea about
multiple errors which single catch. So, sometimes whenever we are not sure about, if any
exception we will occur in our program, then usually programmer will prefer this kind of
things. So, only say one try and one catch that catch will consider or handle only the
object exception e.

So, this is the very simple one approach, of course, sometimes it is, but in some sense
cases whenever we need say details error or exception mechanism, this is not so much
preferable, anyway. So, this is the things that we have learn about simple try-catch, try
with multiple catch, multiple errors with a single catch. Now, in addition to this, there is
another concept, it is called the finally, associated with this try-catch block.
(Refer Slide Time: 12:18)

So, the idea about this finally, is that. So, try-catch we have already learned about it, then
it will contains another block is called the finally. So, it is basically, the idea is that if
there is any exception occurs or not occurs. So, in that case the final you will always
execute for you. So, this means that it always execute this code.

So, this code basically helps the programmer that if an error occurs then, what is the
remedy for that error? So, the programmer can have the flexibility to mention or inform
to the user so that if this is the error occur so what the user should do like this and if we
does not occur you can say that, the program is running successfully, this kind of things.
So, this is an idea about finally.
(Refer Slide Time: 13:14)

Now, let us have a small example to explain the concept of finally, here. Now in this
program, if you see we have declared an array, the name of array is greetings, which will
be initialized with three strings; "Hello Twinkle!", "Hello, Java!", "Hello World!" and so,
it is basically greetings that have the index from 0 to 2 0 1 and 2. Now, here if we run
this y loop then ok, for i equal to 0 1 2 it will work, but for 3 and after that is, it will
basically give an error or exception, this is, because so i greater then, if i equal to 3 and it
will try to find this one right. For i equal to 3 then greetings, because it is 0 1 2 maximum
so 3, in this case, it will gives an error.

So, this loop if we roll, it will roll for first three input 0 1 and 2, but for 3 it will give an
exception. Now, here the finally, catch is basically for each iteration it will, there is no
exception so catch will not do anything, but finally, we will say that whenever i get less
than, greater than 3 it will basically give that error. So, this is the idea about that the final
you will, finally a block can be added in addition to try-catch block, to give more
flexibility to the user. Now, Java also allows programmers to throw exception explicitly.

Now, all this example that we have discussed that, it is basically implicit throw. That
means, whenever the exception, we will occur the Java runtime management manager
basically, we will check it and then try for an exception, if it occurs and then catch it, but
sometimes we can throw the exception of our own. So, this can be done by a throw
clause.
(Refer Slide Time: 15:25)

So, there is a throw clause, it is there. Now for example, here as we see, so this is a
simple try-catch block in a block and here is a throw exception object. So, a different
type of exception and corresponding exception can be thrown by this one. So, this is the
throw clause ok. By writing this throw so far, in our previous example, we have not used
this throw. Now, we are going to use this throw that explicitly, it will throw and
exception objects. Now, this is basically, if you find some error during some input or in
your program or system, then you can throw especially that is why the Java developer
has maintain this kind of concept here.

(Refer Slide Time: 16:11)


Now, let us have an example here. So, a throw can, can also throw many exception that
is also possible and so, there is again, in other than this throw there is also in throws; that
means, if it throws multiple exception. So, this is the idea about, let us have an example
so that we can discuss, we can learn this example and then have the full idea about it.

(Refer Slide Time: 16:39)

Now, this is the one simple program that we can just check it. Now, here we have created
one exception, the name of the exception is my exception and this is basically than
inherited, a superclass of exception actually. So, it is a derived class, superclass
exception. As you know the exception class is already defined in this java.lang package.

So, this is the concept that ok, we have to create an exception class. So, it is basically,
user-created exception class and so what message that this exception class can give to the
user is basically, this is the message and this is the constructor that is defined in the
exception. So, using this constructor is basically overloading and this basically is a
definition of the constructor of this, my exception class, actually.

And so, this part is basically declared an exception class of users own. So, it is the user's
own exception. Now, I will discuss about there are many built-in exception classes are
there. Now, this is the user-defined exception class, anyway. Now, once you defined the
user exception class then you can create an object of that class and here is an example.
Now, if we see this example. So, this is a very simple one.
So, this is the main method as we see and hear the possibility of causes of error it is
there; obviously, y 0, but in this case, you see y is always 1000 static value. So, no, but
sometimes the user can tell that ok, if this ratio is within not a threshold for example, if z
is less than 0.01 and then only you can raise the exception. So, here actually if z, which
will come from this arithmetic operation, is less than this one, then it will throw, this is
the exception with this message.

So, this is the i use of the explicit, throwing an exception in a method and then this is the
catch, as you see, this will catch the exception of this type and then the message, the
block for the catch. And this is the finally, as you have mentioned, that it will always
execute whenever there is an exception occurs or if not occur if there is an exception
occur, you can maintain the code, what it should do and whatever it is there. So, this is
the idea about, that idea about throw clause.

(Refer Slide Time: 19:19)

Now, here is another example of a throw clause that is the same thing. Here we have
declared one class, the name of the class is throw demo and where there is one method
call the demo proc and in this method, we declare our own try block. Here is try, throw a
new interrupted exception. This is basically user-defined exception and interrupt occur
and whatever the code, there is the demo proc and then this exception if it occurs, it will
catch using this catch block and this catch also can throw another expression, is basically
throw and expression to the color program actually, because it is a procedure whenever it
is called, it will throw to the caller actually.

So, now here this is the caller program here which will call this demo to proc and it calls
it. Now, if any exceptions occur, because of some code here, it will throw and this
exception e we will catch. This exception, which is called by this one here also and this
will print like this. So, they are, there are many usages of this throw exception. More
basic concept here is that, it can throw any exception which user wants to, to throw it in
this program so that the program is more robust. So, this is the throw concept there in a
block.

(Refer Slide Time: 20:51)

And there is again throws also possible in exception handling for, to handle the
exception, to handle the exception in a Java program. Now, for this purpose, the Java
program proposes, an idea about it; so, suppose we want to throws an exception,
whatever it occurs in a method. Let this is the name of the method, where we want to
throws multiple exceptions, then you should use throws clause and then whatever the
exception that you have, you anticipate, you can be made it their list.

So, if there is a say array out of bound exception. So, array out of bond exception
comma, if there is a null pointer assignment then comma and so. So, this basic list of all
exception that this throws can throw and so that the corresponding, the catch block will
be there, they can catch it. So, the idea here, it is that this throws command; we will
throw multiple exceptions that may occur in a method.

(Refer Slide Time: 22:06)

Now, so, idea it is now, let us have the one simple example so that we can understand
about this one. Yes, now this program, we have once discussed in our demonstration as
well as while we are discussing about the input-output. As we see, in this program there
are many points, where the exception may occur. Now, let us examine one by one.

So, here is basically if you see, in this part there is no point of exception, but here if you
see, here data inputs stream, in this one. Now, here if suppose, it is not possible to, this
program is not able to create an object of a data stream in, then an exception we will
leads because this in is referred in subsequent here in many a situation. So, if this object
is not created then in the subsequent points, it will raises many exceptions are there at,
this is because Java is basically an interpreted manner.

So, if this, this fails then; obviously, it will not stop here. It will try to give, execute it
and then in every point it will point out the exception, anyway. So, there is a possibility
that here an exception may occur in the sense that that in the data input stream object is
not successfully created for some reason and also system.in, it is basically standard input
sum. Suppose, your keyboard is not working properly while you are running this
program or once the input device is not working, which basically may have to system
end than in that case also this object will not be created.
Now, so, these are the basic system.out.plus there is no point of which basically clean the
buffer the concept it is there. Now, here you see there is again in read line, if suppose this
buffer is not able to read successfully, for some reason then here also there will be an
exception and here also another exception, if the buffer is not able to read at this point
and here is also another exception if the buffer is not able to read at this point ok.

So, we see there are three different points, where the exception occurs and in this
particular example only one particular type of exception occurs. Now, you can define
that exception of your own, if you defined then you can mention that in this throw block.
So, that is exception, but here without taking any, what is called risk, we have discussed
the throw exception, any type of exception, if it occurs, in this particular code, then this
throws will throw an expression expressively and then this catch, will catch this
exception e.

So, the idea about that any exception if it occurs here, this throws as it is mentioned here,
will throw the exception in the try block and then the corresponding exception, will this
one. Now, here if I do not write this one also and only this part, also it will work. This is
a particular case is that, because there is a; obviously, the responsibility of Java runtime
manager. Java manager will automatically take care this part, whenever an exception
occurs, but sometimes the exception, which is basically, as per the requirement of the
program.

Say some (Refer Time: 25:46) in this case it is not working of course, but in some
situations. Say suppose, I am telling you one example say in .read line it is working
correctly, but I want to see that if suppose I have to enter say two-digit number if user
printer one digit. So, in that case, after reading this one I can throw an exception occurs,
according to my own requirement like this one. So, in that case, this throws or here also
after seeing these things, we can write throw.

So, out of this, there are many ways actually. So, we can write this one and then do all
these things. We can have this one, not required, but this one or we do not have this one
here, but throw here, throw here, throw here. So, expressively there are many ways the
exceptions can be handle actually.

So, whatever be the way basic idea is, that all these things should be catch, either using
multiple catch or simple catch, whatever it is there. So, this is the idea the concept for the
throw-in try-catch mechanism. So, we have discussed about many other features
regarding the exception handling in Java and there are many more in this line. they are
basically, we have discussed only few exception handling concepts. Apart from this,
there are many other different exception classes they defined in java.lang package.

So, those things definitely a programmer should know about it then they can use it for a
program in a better wider domain actually if you want to develop it. And there is also
another possibility Java makes more, what is called the flexible in the sense that it allows
a user to define their own exception. Now, in our next module, we will discuss about,
how a user can define their own exception and then those exceptions can be handled and
whatever the built-in exception classes are there in Java program.

Thank you very much.


Programming in Java
Prof. Debasis Samanta
Department of Computer Science and Engineering
Indian Institute of Technology, Kharagpur

Lecture – 25
Exception Handling – III

So, let us learn few more things regarding exception handling in java programming. We
have discussed about the exception handling features mainly the try-catch finally, throw
and throws.

(Refer Slide Time: 00:32)

Now, in this module, we will discuss about the built in the different packages. And
before that we should discuss few more things they are the so that try-catch. So, for try-
catch concept as we have learned about, there is a scope that the nested try-catch can be
implemented. Now, here is an example to include this concept called the nested try-
catch. It is a nested means the try-catch block within another try this is the concepts. So,
and there is no limit of nesting, try-catch block within try, within that try-catch block
another try-catch like this, this. So, and then obviously that what is the reason, what is
the purpose; why you should do that there obviously, it is the questions.

Now, the basic concepts, so for the nested try-catch can be understood here from this. So,
suppose this is a method which is under the investigation of handling exception. And
here if you see there is one what is called the inner try-catch, sorry outer try-catch block,
within this try-catch we can define another try-catch is called the inner, within this also
another try-catch block can be define like this. So, if we define a try-catch block within
another try-catch block, then search a try (Refer Time: 01:49) is called nested try-catch
block.

(Refer Slide Time: 01:57)

Now, let us see one example where it can be applicable. This is again simple example
that we can thing about ok. These are very simple program, it has only main method. So,
you want to handle the exception in this method only. So, here is basically a args dot
length, for the args dot length means whatever the input that user past according the
number of input, this value a will be decide. So, if user do not pass any input, a will be 0;
and accordingly the value of a will be there. Now, here if user do not pass any input, then
a is 0; and as we see there is an exception call divide by 0 or arithmetic exception.

Now, again let us see here, suppose user enter only one input, so in that case a equals to
1. Now, in that case also it will give an error. So, it is also the divide by 0 error. Now,
another situation so it is not the 0 input it is not the single input. So, suppose user enter
two input, the in that case if you see if a equals to 2, then there is again possibility of
error, because here we declare an array of integer c with only one element c need, that
means, size of the array at represent is one, but we want to store a value at the second,
that means, this is array index out of bound error is there.
Now, so here basically two type of errors. In the first two cases as we see here and here,
this arithmetic exception error; and in the second case is there is called the array index
out of bound exception occurred, so two type of error. Now, if two type of errors, then
we can think for only two catch block. Now, here the idea is that we can write one try
block here. So, this catch block, this try-catch block will handle these are the arithmetic
exception error. Then there is another error that may occur within this, so inside this
another try-catch block we can put, so that it can handle this exception. So, this is a
concept, this is a concept of nesting. So, this is a simple example.

(Refer Slide Time: 04:11)

So, here is a solution for the nesting case is there. As we see this program will not run for
all the input because it will give an error whatever it is there. It will run for this one no
error, but for this one it will error.
(Refer Slide Time: 04:26)

Now, so the remedy here we have checked it here. So, let us see this program as we have
see this is the try and corresponding to this. So, this is there is a two try-catch block. As
we see in this program this is the one try and this is the corresponding catch, so try-catch
and this is a inner try-catch. And outside this, this is another try and this is another catch.
So, so it is called the nested try-catch. Now, if we see this inner try-catch, we will handle
the exception, this is the array index out of bond. Whereas, this try will handle the case
this one, and then finally, this is work. So, this is idea about the nested try-catch block.

So, java is basically is a very versatile programming language in the sense that whatever
the possible exception and errors may occur in a program, it can handle. So, regarding
this things, the java developer or jdk package includes a very nice one package java dot
lang package. This package has been planned to, so that it can take care many errors and
exception.
(Refer Slide Time: 05:46)

So, this is the class hierarchy that this java lang package has regarding that exception
handling. So, here basically there is a class called object is defined in this java dot lang.
Throwable class, it is called the class throwable. Under this Throwable, these are the
basically hierarchy of the different sub classes of the class Throwable. So, object is the
class super class under the super class Throwable is basically another inter. And this
throwable has many at so this basically Throwable class as the two sub classes Error and
Exception. Now, the simple exception is there, and then runtime exception is there now.
So, so these are the different what is called the class hierarchy that is there in the java dot
lang dot Throwable classes are there. Now, for each classes there are different what is
called the exceptions that may occurs under this classes, so that they can handle it.
(Refer Slide Time: 07:03)

So, here is basically let us first discuss about the runtime exceptions sub classes which
basically causes many exception. So, I exceptions are discussed here. As we see here that
five around ok, so around 12, 18th, 18th, 6, 6, 12 ok. So, 12 different type of exception
that may occur during runtime exception sub classes which it can cause.

For example, we have already discussed about array arithmetic exception, array index
out of bound exception, and then there is a many more array this illegal argument
exception, security exception, incompatible class change error index out of bound
exception negative array size exception, null pointer exception, number format
exception, string index out of bound exception, few exception already we have discussed
in our discussion and few more exception that we will learn about while we have a
demonstration on this concept, so that it will clear our idea.

Now, so these are the different type of exceptions that the java developer automatically
these are built in exception types which is already there in the runtime exception
category of the Throwable class. Now, so these are the frequently occur exception related
to the different situations it is there.
(Refer Slide Time: 08:27)

Now, other also there is another class exception sub class also there. It is basically in this
exception sub class, there are few more exception that it may handle is a ClassNotFound
Exception, and then DataFormatException, IllegalAccessException, Instantiation
Exception, InterruptedException, NoSuchMethodException and RuntimeException.

So, these are the different type of exception it is usually if you are an advance java
programmer, then he may phase this kind of exception when you are developing
applications. So, in that case all the coming to the picture, but it is very difficult to
illustrate all this exception one by one, because it is too more I mean it is also not
possible in this shortest time anyway. So, these are the different exception. So, for
RuntimeException and then exception sub classes is concern and there is one is called
the Error sub class.
(Refer Slide Time: 09:24)

So, in the error sub class also, you can see these are the different exception that it may
occur ok. So, this is the error classes, and this is the exception sub classes.

(Refer Slide Time: 09:44)

So, these are the few more errors that is there in the exception classes as we have
mentioned here that ClassCirculatoryError,ClassFormatError, Error, simple error, and
then LinkageError, InstantiationError, NoClassDefineFound Error, NoSuchMethod
Error, NoSuchFieldError, OutofMemoryError, StackoverFlowError,
Throwable ,UnknownError, UninsatisfiedLinkError, then VerifyError and
VirtualMachineError. So, there are many errors that may occur in a program which is
discussed here.

(Refer Slide Time: 10:26)

Now, all these sub classes that we have discussed is associated with many methods. Here
we have listed few methods, and with their description. As you see here they get
Message probably you have run about the getMessage is basically it will tell about a
particular error. So, it is it basically returns a message about a particular exception that
usually it over an encounter. So, it is basically this message is initialized through a
constructor which is defined in Throwable class; this is the main class, super class.

Now, there is again get cause, it basically a return an object of class Throwable to the
caller program if a method in which this exception occur, it will basically throw a throw
an exception to the caller, so that is why get cause it basically tell about the reason for
the exception that it have. So, it has very useful indication to both the programmer as
well as for the user also. Then to string here it basically return the name of the class
where this error occurs. It possibly concatenated if this class is under another class or is a
nested class or derived class or whatever it is there, it will basically concatenated, all the
classes then give a particular location. So, this is particularly very much useful for
debugging, debugging the program and testing the program.

Then printStackTrace it is just like a idea about tracing there that means, if an error
occurs in a particular method. If this method is declared in which class if this class is a
derived class or not or implements and interfaces like this. So, it will basically give a full
trace off the location where this particular exception occurs. Or if there is a chain of
exception one exception can propel other exception, then other exception also using this
printStackTrace, we will be able to trace the reason or the location of the exception.

Then stack trace element, it is basically and advanced version of this one, it basically it
multiple errors are occurs, then it basically put on into the stack whenever we writing
same recursive program suppose and there maybe multiple exception occurs in a
different points. And then it will basically (Refer Time: 13:11) all the exception into a
stack, and that is basically the idea about. And then finally, it will use this one.

So, this get stack trace is basically catch all the exception that it may happen in a method,
and it will push on stacking actually it is stacking into a stack. And then fill in
StackTrace also it basically this method returns a object returns and exception object of
this throwable class. And whenever there is an exception occurs, and then obviously, in
the so it basically think that whether stack is able to maintain handle this kind of
exception or not. So, this is the (Refer Time: 13:56) is statement like. So, these are the
different methods which are there in the exception class.

Now there is a possibility, so that depending on the needs of user, user can define their
own exception. So, this concept is basically to make the program, more versatile, more
flexible more robust and reliable. So, this is possible by means of user defined exception,
in other words user can define their own exception.
(Refer Slide Time: 14:35)

So, here is an idea, let us see how user can define their own exception. Now, first of all
you have to create a class that class should be a derived class of the super class
throwable. So, it is basically all exception must be a child of Throwable class. We have
already discussed about this throwable class is defined in java.lang package. Now, so this
is the syntax by which we can create an exception which basically type of the runtime
exception that can handle it.

So, here as we see class, myException it is basically user defined class. And extend
Exception, Exception is basically is a sub class of Throwable, we have already learned
about. And sometime the RuntimeException also we can declare, so there are different
type ok. So, so this is the way by which user can define their class, and here the code of
the exception class. Now, let us have an example, so that we can understand how user
can define his own exception.
(Refer Slide Time: 15:46)

Now, this is the very simple program. And here we can see this is the user defined one
class. This is the user defined one class. We define the name of the class that we have
define is InsufficientFundsException which basically is a derived class of exception. And
these are the a few quotes of this right. So, here private double amount is a one field, and
then this is basically the constructor of this class, this will take the amount. And this dot
amount it basically initialize. And then there is an another method public double
getAmount( ) and returnAmount().

So, so the class is very simple. Without any exception this class can be considered only
simple class a and then all this course can also be there. But we have to just make it
attend exception class, this one of our own. Now, let us see how we can use it this is a
one application that we are going to discuss in the context of banking transaction and
then we can understand about it. Let us have the discussion so that we can discuss about
it.
(Refer Slide Time: 17:05)

Now, so this exception that we have discussed here we want to use it in our application
class. Now, so application class is like this. So, there is a user defined class Checking
Amount, checkingAccount. So, it will take the balance, then number, and then it is a
constructor here. And this is another method deposit amount and the balance will be
increased. So, this is a concept it is there. So, it account will be checked, and then the
amount that will be deposited will be deposited into the account. And there is another
method which is in this class is also there withdraw method, deposit method, withdraw
method. And here in this case we have mentioned one exception throws, throws
InsufficientFundsException .So, if we can find that if amount less than equals to balance,
then balance will be negative or balance will be adjusted, and then if it is not, then it will
throw an exception. So, this exception is basically it is there. So, suppose user one user
wants to withdraw some amount which is not permissible as per the balance is concern,
in that case it will throw this exception insufficient funds exception. So, this is the idea
about.

Then once this class is declared, we can use we can define the main class here. Here you
can see this is an extension of this one just ok, withdraw has this one else and this class
has few more course of course. So, here is few course it is there. And then these are the
simple getBalance and then getNumber, these are the complete description of the class
has it is there, checking account class. Now, on this class is defined, then we will be able
to define our main class.
(Refer Slide Time: 19:00)

So, the main class it looks like this the name of the main class is BankDemo, and it has
the main method. And we can see we have created an object of checkingAccount and
then say let there may be 100 plus the account holder is there. So, these are size of the
total customer base actually. And then system.out.println depositing dollar 500, this is a
one method it is there. And then see deposit 500, so it is basically that ok. This for this
object we want to write call the method deposit.

So, now, after this thing try catch is there, and then c.withdraw. So, this is the 100
withdraw one instance, 600 withdraw another instance. Now, in case, suppose there is
any exception occur, then this is a catch block which will take care. So, this is our the
fund exception, user defined exception as you can note it here

Now, so there are few instances that it may occur. If you run this program the entire
class declaration that we have discussed and then run it. And then there are few instances
of the input that we can see depositing dollar 500, withdrawing dollar 100, these are the
things that we will sorry, but you are short of 200, insufficient funds exception at this
one, it basically shows the different situation when this program is executed.

So, this way you the user can define their own exception, and then can develop the
program according to their requirement ok. So, this is about the different cases of the
exception that it may occur here. And we are almost at the final round of the exception
handling discussion. Before going to this things I just want to mention few a simple
example, let us see whether you can follow it or not.

(Refer Slide Time: 21:05)

Here is the one program and just took a check this program and tell where is the possible
scope of exception that it may result. As we see here so this is a simple class only one
class which has the main method, this is the main method. Now, let us can one by one
this statement. Now, I am telling one very simple rule of thumb is that if we suspect any
exception that it may results, then that statement that code can be put under try-catch. So,
in that catch, the very simple way that you can handle the exception is that so many try-
catch corresponding this one, but this is obviously, makes the program to so many try-
catch, but ultimately it is a robust of course.

But there are many way that is the rather efficient way that with minimum number of try-
catch how we can handle everything. So, usually the advanced programmer think for this
one that with minimum number of try-catch, whether this is try-catch nested, throws-
throws you, with your own exception, whatever it is there, anyway. So, for a beginners,
the best practice should be that if you see that there is an error so put a try-catch and
accordingly handle it, you can use the finally, if you want if you do not want, then final
is a default one. So, it is not necessary to use.

Now, so here again here if you see this is the one statement, do you think that there is a
possibility of an exception occurred here. Yes, because if the Scanner class is not
instantiated, and then create a scanner object, then it may leads to an exception. So, there
is a possibility that an exception occurs. So, this is a one possibility that exception occur.

Now, next is here this statement and this statement as well as. So, nextInt is basically it
check that in the line of input, whether the next input is there. If some regions are there,
whenever this input is not there or not able to read integer rather some string and
everything, then this statement also throws exception. And these are the very simple. So,
there is no exception.

Now, so these are the point here, here, and here. Now, how many try-catch block that
you can think for fine. So, one solution is that, all these things put can be put only try,
and then here is the catch or as it is a try this is the one kind of exception and this is the
only kind of exception. So, nested try also can be plan, so that with minimum number of
try-catch code, we can handle the exception here in this case. So, it is the practice.

So, you can think about how you can put it. It is basically if you put many try-catch
block, absolutely no error, no problem, because if the exception occurred then only it
will be there. But the problem is that if you do not mention try-catch block properly, so
that even in the case of exception occurred you are not able to catch it, then it is a
problem, so that is a things are there.

And one more thing, so if you do not put try-catch block explicitly, but there is a
possibility of exception occurs. So, during the compilation, the compiler can note it and
then compiler can report it. Until you put try-catch in your block, compiler is not compile
it successfully. So, this is the one great advantage for the programmer that ok, if you are
supposed miss to add try-catch construct in your program, the compiler will help you to
do that. So, there are many ways it is possible. So, this is the one example that we have
discussed about in a scanner, and this is simple one example.
(Refer Slide Time: 25:07)

Now, let us consider another example. It basically is similar to the Scanner. This Scanner
means it is basically read the input from the keyboard, and then store into an array. Here
is an example as we see. And array list is a one structure data structure defined in
java.util package. Now, let us see here. So, so this is a simple again code, the main
method. And obviously, there is no point of exception, but here is a one point of
exception that if the array list is not this l not built in properly or not created
successfully. If it is not created successfully, then here is an error occurs, here is an error
occurs, and then here is an error occurs. And also here another error occurs that l.size if
you have created an array list, but this size of the array list is very small rather is a 0,
then also it can created, it can creates errors.

Now, we have pointed out few things are there, again another also there is also
possibility that one error is occur here. Now, again if I ask you that ok, how you can
insert the try-catch block in this program, so that this program will be robust or if you
can think about of your own throw, and then accordingly user-defined exception you can.
So, if you want to have your own user-defined one, you should defined a exception
classes which is a child class derived class of throwable or exception, and then according
to that you can write the try, here the try, here the catch or here again try another catch,
so that all the exception it can be handled in this program. So, the many ways actually
that you can do. So, this is the one idea about.
(Refer Slide Time: 27:09)

Now, let us have another example ah. So, here is another example. And this example we
have discussed while we are considering input and output to the system. This example as
we see here we have fine, this is again simple method main method it is there. In this
main method, these are the simple declaration of the two objects. So, this is also another
declaration. So, these are declaration. There is no point of any exception occurs here just
a matter of discussion a declaration only.

Now, here if we see here again this one this basically is the one very critical code here,
because we have to create an object of data input stream and sometimes this may have
problem. Sometimes I told you, not always, and exception is like that it can happen in
some special situation like this. Now, in that case, so this statement should be covered
under try-catch block. Now, if there is a problem and subsequently, they are also the
possibility that there is a problem here either it is a readLine problem from the object in.
There is also a readLine from the object in; there is also there and like this ok. So, one,
two, three, four, the four points where we can see the exception occurs here..

And also here, so this is basically this is the one value of changing conversation string to
float value, string to integer to parse in there is also possible scope of errors there. Now,
as we see as they these are the possible, because you have entered some value which is
not possible to convert an integer say 2 0 20.55, then in that case it basically not able to
parse into integer, so that error will be there. So, as you see, so these are the four cases
and this also other three cases that error may occur.

Now, once you identify this is a possible location that the exception can be thrown or
exception can occur, then accordingly we have to take care about that try-catch. There
are again many ways are there. First of all we can use the throw statement. So, what we
can do is that, we can write here the throws, throws and exception. Then what about the
causes are there, we can put try and then here catch, so try and then catch, then exception
occur (Refer Time: 29:57). So, this is the one way. So, throws means it will basically
throw all the exception that it may happens and then using this try-catch they can be
exception.

Now, other than using the throw statement itself simply try and then the catch also can be
put here exception. If you can know that this is the exception due to this, this is the
exception due to this, then accordingly several catch block several catch block you can
put it for each exception. So, this is a case of single try with multiple catch. And also one
try with all exception in multiple exceptions by one catch also in that case similar to the
throws also we can use it. So, in the many ways, many ways that you can do only if you
know the mechanism, then all those ways that can be incorporated in your program, and
thus you can make your program very robust.

(Refer Slide Time: 30:56)


So, this is all about the exception handling concept in java programming. Now, after
knowing the exception mechanism; our next tasks to learn about how the distributed
programming can be done because java is very famous for distributed computing. So, in
our next model, we will learn about the distributed programming more specifically the
multithreading concept. And then, we will discussed the how java right language can
helps a programmer to develop their internet programs. So, these are the concepts these
are, I mean questions will be answer in our next module (Refer Time: 31:45).

Thank you very much.

You might also like