0% found this document useful (0 votes)
33 views

Exception Handling and Collections

The document discusses exception handling in Java and collections. Exception handling covers checked, unchecked exceptions and errors. Collections discusses interfaces like Collection, List, Set, Map and cursors like Enumeration, Iterator and ListIterator.

Uploaded by

hari chandan
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
33 views

Exception Handling and Collections

The document discusses exception handling in Java and collections. Exception handling covers checked, unchecked exceptions and errors. Collections discusses interfaces like Collection, List, Set, Map and cursors like Enumeration, Iterator and ListIterator.

Uploaded by

hari chandan
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 28

Exception Handling and Collections

Exception Handling
What is Exception in Java?

In Java, an exception is an event that disrupts the normal flow of the program. It is an object which is thrown at runtime.

Types of Exception

1) Checked Exception: The classes which directly inherit Throwable class except RuntimeException and Error are known as
checked exceptions like IOException, SQLException etc. Checked exceptions are checked at compile-time.

2) Unchecked Exception: The classes which inherit RuntimeException are known as unchecked exceptions like
ArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException etc. Unchecked exceptions are not checked at
compile-time, but they are checked at runtime.

Error: Error is irrecoverable like OutOfMemoryError, VirtualMachineError, AssertionError etc.


Example: Suppose our programming requirement is to read data from remote file locating at London. At runtime if London file is not available then our program
should not be terminated abnormally. We have to provide a local file to continue rest of the program normally. This way of defining alternative is nothing but
exception handling.

Example:

try {

read data from London file

catch(FileNotFoundException e) {

use local file and continue rest of the program normally

Runtime Stack Mechanism: For every thread JVM will create a separate stack at the time of Thread creation. All method calls performed by that thread will be
stored in that stack. Each entry in the stack is called "Activation record" (or) "stack frame". After completing every method call JVM removes the corresponding
entry from the stack. After completing all method calls JVM destroys the empty stack and terminates the program normally.
Customized Exception Handling by using try-catch:

It is highly recommended to handle exceptions.


In our program the code which may raise exception is called risky code, we have to place risky code inside try block
and the corresponding handling code inside catch block.
Example:

try
{
Risky code
}
catch(Exception e)
{
Handling code
}
Try with multiple catch blocks:

The way of handling an exception is varied from exception to exception. Hence for every exception type it is recommended to take a separate catch block. That is try with multiple
catch blocks is possible and recommended to use.
try
{
.
.
.
.
catch(FileNotFoundException e)
{
use local file
}
catch(ArithmeticException e)
{
perform these Arithmetic operations
}
catch(SQLException e)
{

don't use oracle db, use mysqldb


}
catch(Exception e)
{
default handler
}
Finally block:
It is not recommended to take clean up code inside try block because there is no guarantee for the execution of every statement inside a try.
It is not recommended to place clean up code inside catch block because if there is no exception then catch block won't be executed.
We require some place to maintain clean up code which should be executed always irrespective of whether exception raised or not raised and whether handled or not
handled. Such type of best place is nothing but finally block.
Hence the main objective of finally block is to maintain cleanup code.
Example:

try
{
risky code
}
catch(x e)
{
handling code
}
finally
{
cleanup code
}

The speciality of finally block is it will be executed always irrespective of whether the exception raised or not raised and whether handled or not handled.
Difference between final, finally, and finalize:

final:

final is the modifier applicable for classes, methods and variables.


If a class declared as the final then child class creation is not possible.
If a method declared as the final then overriding of that method is not possible. If a variable declared as the final
then reassignment is not possible.
finally:

finally is the block always associated with try-catch to maintain clean up code which should be executed always
irrespective of whether exception raised or not raised and whether handled or not handled.

finalize:

finalize is a method, always invoked by Garbage Collector just before destroying an object to perform cleanup
activities.
throw statement:

Sometimes we can create Exception object explicitly and we can hand over to the JVM manually by using throw keyword.

Example:
class Test
{
public static void main(String[]
args){
throw new ArithmeticException("/
by zero");
}}
Collection
1. If we want to represent a group of "individual objects" as a single entity then we should go for
collection.
2. In general we can consider collection as root interface of entire collection framework.
3. Collection interface defines the most common methods which can be applicable for any collection
object.
4. There is no concrete class which implements Collection interface directly.
9(Nine) key interfaces of collection framework:

1. Collection
2. List
3. Set
4. SortedSet
5. NavigableSet
6. Queue
7. Map
8. SortedMap
9. NavigableMap
List Interface
List:

1. It is the child interface of Collection.


2. If we want to represent a group of individual objects as a single entity where "duplicates are allow and
insertion order must be preserved" then we should go for List interface.
ArrayList:

ArrayList:

1. The underlying data structure is resizable array (or) growable array.


2. Duplicate objects are allowed.
3. Insertion order preserved.
4. Heterogeneous objects are allowed.(except TreeSet , TreeMap every where heterogenious objects
are allowed)
5. Null insertion is possible.
import java.util.*; class ArrayListDemo
{
public static void main(String[] args)
{
ArrayList a=new ArrayList();
a.add("A");
a.add(10);
a.add("A");
a.add(null);
System.out.println(a);//[A, 10, A, null]
a.remove(2);
System.out.println(a);//[A, 10, null]
a.add(2,"m");
a.add("n");
System.out.println(a);//[A, 10, m, null, n]
}
}
LinkedList
1. The underlying data structure is double LinkedList
2. If our frequent operation is insertion (or) deletion in the middle then LinkedList is the best choice.
3. If our frequent operation is retrieval operation then LinkedList is worst choice.
4. Duplicate objects are allowed.
5. Insertion order is preserved.
6. Heterogeneous objects are allowed.
7. Null insertion is possible.
8. Implements Serializable and Cloneable interfaces but not RandomAccess.
SET Interface
1. It is the child interface of Collection.
2. If we want to represent a group of individual objects as single entity "where duplicates are not allow
and insertion order is not preserved" then we should go for Set interface.
SortedSet

SortedSet:

1. It is the child interface of Set.


2. If we want to represent a group of individual objects as single entity "where duplicates are not allow but
all objects will be insertion according to some sorting order then we should go for SortedSet.
(or)
3. If we want to represent a group of "unique objects" according to some sorting order then we should
go for SortedSet.
NavigableSet & Queue:

NavigableSet:

1. It is the child interface of SortedSet.


2. It provides several methods for navigation purposes.

Queue:

1. It is the child interface of Collection.


If we want to represent a group of individual objects prior to processing then we should go for queue concept
MAP Interface
1. Map is not child interface of Collection.
2. If we want to represent a group of objects as key-value pairs then we should go for Map interface.
3. Duplicate keys are not allowed but values can be duplicated.
cursors

The 3 cursors of java:

If we want to get objects one by one from the collection then we should go for cursor. There are 3 types of
cursors available in java. They are:

1. Enumeration
2. Iterator
ListIterator
Enumeration:

1. We can use Enumeration to get objects one by one from the legacy collection objects.
2. We can create Enumeration object by using elements() method. public Enumeration
elements();
Enumeration e=v.elements(); using Vector Object
Iterator

Iterator:

1. We can use Iterator to get objects one by one from any collection object.
2. We can apply Iterator concept for any collection object and it is a universal cursor.
3. While iterating the objects by Iterator we can perform both read and remove operations.
ListIterator:

1. ListIterator is the child interface of Iterator.


2. By using listIterator we can move either to the forward direction (or) to the backward direction that
is it is a bi-directional cursor.
3. While iterating by listIterator we can perform replacement and addition of new objects in addition to
read and remove operations

You might also like