UNIT-05
Exception Handling and Generic Programming
Sachin D. Shelke
Inheritance and Polymorphism
Exceptions: Errors, Types of Errors, Exception and its Types, Exception-Handling
Fundamentals, Uncaught Exception, Using try and Catch, Multiple Catch Clauses,
Nested Try Statements, User Define Exception using Throw.
Generics: What are Generics? Introduction to Language Specific Collection Interface:
List Interface and Set Interface, Collection Classes: ArrayList Class and LinkedList
Class.
Case Study: Exception handling and generic programming using array list
(ArrayList class)
Exception
Errors: deviation from expected result
Types of Errors:
Compile-time Errors
Runtime
Sytax Errors, Semantic Errors, Logical Errors etc.
Exception
Exception is an abnormal condition that arises in a code sequence at run time.
Exception is a run-time error.
Types of Exceptions:
Built-in Exceptions
User-defined Exceptions
Built-in Exception
1) Arithmetic Exception
2) ArrayIndexOutOfBoundsException
3) ClassNotFoundException
4) FileNotFoundException
5) IOException
6) InterruptedException
7) NoSuchFieldException
Built-in Exception
8) NoSuchMethodException
9) NullPointerException
10)NumberFormatException
11)RuntimeException
12)StringIndexOutOfBoundsException
Built-in Exception
class ArithmeticException_Demo
{
class ArithmeticException_Demo public static void main(String args[])
{ {
try {
public static void main(String args[]) int a = 30, b = 0;
{ int c = a/b; // cannot divide by zero
int a = 30, b = 0; System.out.println ("Result = " + c);
}
int c = a/b; // cannot divide by zero catch(ArithmeticException e) {
System.out.println ("Result = " + c); System.out.println ("Can't divide a number by
0");
} }
} }
}
Built-in Exception
class ArrayIndexOutOfBound_Demo
class ArrayIndexOutOfBound_Demo {
public static void main(String args[])
{ {
public static void main(String try{
int a[] = new int[5];
args[]) a[6] = 9; // accessing 7th element in an array of
{ }
// size 5
int a[] = new int[5]; catch(ArrayIndexOutOfBoundsException e){
System.out.println ("Array Index is Out Of
a[6] = 9; // accessing 7th element Bounds");
} }
}
} }
Exception Types
Throwable
Exception
Error
RuntimeException
Uncaught Exception
class Exc0 {
public static void main(String args[]) {
int d = 0;
int a = 42 / d;
}
}
Java run-time system detects attempt to divide by zero, it constructs a new exception object and
throws this exception. This causes exectution of Exc0 to stop, because once an exception has been
thrown, it must be caught by an exception handler.
Using try and catch
Although default exception handler is provided by java run-time system,
usually, we want to handle an exception ourself.
Advantages:
It allows you to fix the error.
It prevents the program from automatically terminating.
Using try and catch
class Exc2 {
public static void main(String args[]) {
int d, a;
try { // monitor a block of code.
d = 0;
Division by zero.
a = 42 / d;
System.out.println("This will not be printed.");
After catch statement.
} catch (ArithmeticException e) { // catch divide-
by-zero error
System.out.println("Division by zero.");
}
System.out.println("After catch statement.");
}
}
Displaying the Description
class Exc2 {
public static void main(String args[]) {
int d, a;
try { // monitor a block of code.
Exception:
d = 0; java.lang.ArithmeticException: /
a = 42 / d;
System.out.println("This will not be printed.");
by zero
} catch (ArithmeticException e) { // catch divide-
by-zero error
After catch statement.
System.out.println("Exception "+e );
}
System.out.println("After catch statement.");
}
}
NumberFormatException
class empdemo{
import java.io.*;
public static void main(String args[]) throws IOException{
String name;
class Employee{
int id;
try{
String ename; BufferedReader reader =new BufferedReader(new
int eid; InputStreamReader(System.in));
name = reader.readLine();
Employee(String name, int id){ id = Integer.parseInt(reader.readLine());
ename= name;
eid= id; Employee e = new Employee(name,id);
} e.display();
void display(){
System.out.println("Employee Name: }catch(NumberFormatException e){
"+ename); System.out.println("Error: "+e);
System.out.println("Employee id: "+eid); }
}
} }
}
NumberFormatException
class NF{
public static void main(String args[]){
try{
Scanner s = new Scanner(System.in);
String name = s.next();
System.out.println("Name: "+name);
int id = Integer.parseInt(s.next());
System.out.println("ID: "+id);
}catch(NumberFormatException e){
System.out.println("Exception: "+e);
}
}
}
Multiple catch Clauses
In some cases, more than one could be raised by sigle piece of code. To handle this
type of situation, you can specify two or more catch clauses, each catching a
different type of exception.
When an exception is thrown, each catch statement is inspected in order, and the
first one whose type matches that of the exception is executed.
After one catch statement executes, the others are bypassed, and execution
continues after the try/catch block.
Multiple catch Clauses
/ Demonstrate multiple catch statements.
C:\>java MultiCatch
class MultiCatch {
a=0
public static void main(String args[]) {
Try {
Divide by 0: java.lang.ArithmeticException: / by
int a = args.length; zero
System.out.println("a = " + a);
After try/catch blocks.
int b = 42 / a;
int c[] = { 1 };
c[42] = 99;
C:\>java MultiCatch TestArg
} catch(ArithmeticException e) {
a=1
System.out.println("Divide by 0: " + e);
} catch(ArrayIndexOutOfBoundsException e) {
Array index oob:
System.out.println("Array index oob: " + e); java.lang.ArrayIndexOutOfBoundsException:42
}
After try/catch blocks
System.out.println("After try/catch blocks.");
}
}
Multiple catch Clauses
When you use multiple catch statements, exception subclasses must come before
any of their superclasses. This is because a catch statement that uses a superclass
will catch exceptions of that type plus any of its subclasses.
Further, in Java, unreachable code is an error.
Multiple catch Clauses
class SuperSubCatch {
public static void main(String args[]) {
try {
int a = 0;
int b = 42 / a;
} catch(Exception e) {
System.out.println("Generic Exception catch.");
}
/* This catch is never reached because ArithmeticException is a subclass of Exception. */
catch(ArithmeticException e) { // ERROR – unreachable System.out.println("This is never reached.");
}
}
}
Nested try statements
// An example of nested try statements. try { // nested try block
class NestTry { if(a==2) {
public static void main(String args[]) { int c[] = { 1 };
try { c[42] = 99; // generate an out-of-bounds
int a = args.length; exception
/* If no command-line args are present,
}
the following statement will generate
a divide-by-zero exception. */
} catch(ArrayIndexOutOfBoundsException e) {
int b = 42 / a; System.out.println("Array index out-of-bounds: "
System.out.println("a = " + a); + e);
}
} catch(ArithmeticException e) {
System.out.println("Divide by 0: " + e);
}
}
}
Nested try statements
C:\>java NestTry
Divide by 0: java.lang.ArithmeticException: / by zero
C:\>java NestTry One
a=1
Divide by 0: java.lang.ArithmeticException: / by zero
C:\>java NestTry One Two
a=2
Array index out-of-bounds:
java.lang.ArrayIndexOutOfBoundsException:42
throw
We can catch the exceptions that are thrown by Java run-time system.
We can throw an exception explicitly, using throw statement. The general
form of throw is
throw ThrowableInstance
ThrowableInstance must be an object of type Throwable or a subclass of
Throwable.
Example
throw
throw
throws
If a method is capable of causing an exception that it does not handle, it must specify this
behavior so that callers of the method can guard themselves against that exception.
type method-name(parameter-list) throws exception-list{
// body of method
Here, exception-list is a comma-separated list of the exceptions that a method can throw.
throws
throws
Finally
When exceptions are thrown, execution in a method takes a rather abrupt,
nonlinear path that alters the normal flow through the method.
The finally keyword is designed to address this contingency.
finally creates a block of code that will be executed after a try/catch block
has completed and before the code following the try/catch block.
The finally block will execute whether or not an exception is thrown
Generics
A class, interface, or method that operates on a parameterized type is called
generic, as in generic class or generic method.
Generics
Generics
Generics class with Two Type
Parameters
General form of Generics Class
class Gen<T>
Here, T is the name of a type parameter. This name is used as a placeholder
for the actual type that will be passed to Gen when an object is created.
Syntax:
Declaration of Generic Class:
class class-name<type-param-list> { // ...
Declaration of Reference to the Generic Class
class-name<type-arg-list> var-name = new class-name<type-arg-list>(cons-arg-list);
Generics Method
Methods inside a generic class can make use of a class’ type parameter and
are, therefore, automatically generic relative to the type parameter.
However, it is possible to declare a generic method that uses one or more type
parameters of its own.
Furthermore, it is possible to create a generic method that is enclosed within a
non-generic class.
Syntax:
<type-param-list> ret-type meth-name(param-list) { // ...
<T, V > boolean isIn(T x, V[] y) {
Generics Method......Example
Generics Method......Example
Generics Constructor......Example
Generics Interface......Example
Collection Framework
The Collections Framework is a sophisticated hierarchy of interfaces and
classes that provide state-of-the-art technology for managing groups of
objects.
The Java Collections Framework standardizes the way in which groups of
objects are handled by your programs.
Collection Framework
The Collections Framework was designed to meet several goals
First, the framework had to be high-performance.
The implementations for the fundamental collections (dynamic arrays, linked lists, trees, and hash tables) are
highly efficient.
Second, the framework had to allow different types of collections to work in a
similar manner and with a high degree of interoperability.
Third, extending and/or adapting a collection had to be easy.
Collection Interface
List Interface
Set Interface
List Interface
The List interface extends Collection and declares the behavior of a collection
that stores a sequence of elements.
Elements can be inserted or accessed by their position in the list, using a zero-
based index. A list may contain duplicate elements.
List is a generic interface that has this declaration:
interface List<E>
Here, E specifies the type of objects that the list will hold.
List Interface
Set Interface
The Set interface defines a set.
It extends Collection and declares the behavior of a collection that does not
allow duplicate elements.
Therefore, the add( ) method returns false if an attempt is made to add
duplicate elements to a set.
Set is a generic interface that has this declaration:
interface Set<E>
Here, E specifies the type of objects that the set will hold.
Set Interface
The SortedSet Interface: The SortedSet interface extends Set and declares the
behavior of a set sorted in ascending order.
NavigableSet Interface:It extends SortedSet and declares the behavior of a
collection that supports the retrieval of elements based on the closest match to a
given value or values
Set Interface
Set Interface
Collection Classes
Some of the classes provide full implementations that can be used as-is.
Others are abstract, providing skeletal implementations that are used as
starting points for creating concrete collections.
Collection Classes
Collection Classes
ArrayList Class
LinkedList Class.
ArrayList Class
The ArrayList class extends AbstractList and implements the List interface.
ArrayList is a generic class that has this declaration:
class ArrayList<E>
Here, E specifies the type of objects that the list will hold
ArrayList supports dynamic arrays that can grow as needed.
ArrayList Class
ArrayList has the constructors shown here:
ArrayList( )
ArrayList(Collection<? extends E> c)
ArrayList(int capacity)
The first constructor builds an empty array list.
The second constructor builds an array list that is initialized with the elements of the
collection c.
The third constructor builds an array list that has the specified initial capacity.
ArrayList Class..........Example
ArrayList Class..........Example
LinkedList Class
The LinkedList class extends AbstractSequentialList and implements the List,
Deque, and Queue interfaces.
It provides a linked-list data structure.
LinkedList is a generic class that has this declaration:
class LinkedList<E>
Here, E specifies the type of objects that the list will hold
LinkedList Class
Assignment 7
Case Study:
Exception handling and generic programming using array list
(ArrayList class)
References
1. Java Complete Reference
2. Geeksforgeeks.org
3. Javapoint.com
4. Btechsmartclass.com
5. Mygreatlearning.com