JAVA Unit-3
JAVA Unit-3
EXCEPTION HANDLING
Exception
“Exception is an abnormal condition. In java, exception is an event that disrupts
the normal flow of the program. It is an object which is thrown at runtime.”
Types of Exception
There are mainly two types of exceptions: checked and unchecked where error is
considered as unchecked exception.
2) Unchecked Exception
The classes that extend RuntimeException are known as unchecked
exceptions e.g. ArithmeticException, NullPointerException,
ArrayIndexOutOfBoundsException etc. Unchecked exceptions are not
checked at compile-time rather they are checked at runtime.
3) Error
Error is irrecoverable e.g. OutOfMemoryError, VirtualMachineError,
AssertionError etc.
Built-in Exceptions
Java defines several exception classes inside the standard packagejava.lang.
The most general of these exceptions are subclasses of the standard type
RuntimeException. Since java.lang is implicitly imported into all Java programs,
most exceptions derived from RuntimeException are automatically available.
Java defines several other types of exceptions that relate to its various class
libraries. Following is the list of Java Unchecked RuntimeException.
Exception Description
ArithmeticException Arithmetic error, such as divide-
by-zero.
ArrayIndexOutOfBoundsException Array index is out-of-bounds.
ArrayStoreException Assignment to an array element
of an incompatible type.
ClassCastException Invalid cast.
IllegalArgumentException Illegal argument used to invoke a
method.
IllegalMonitorStateException Illegal monitor operation, such as
waiting on an unlocked thread.
IllegalStateException Environment or application is in
incorrect state.
IllegalThreadStateException Requested operation not
compatible with current thread
state.
IndexOutOfBoundsException Some type of index is out-of-
bounds.
NegativeArraySizeException Array created with a negative
size.
NullPointerException Invalid use of a null reference.
NumberFormatException Invalid conversion of a string to a
numeric format.
SecurityException Attempt to violate security.
StringIndexOutOfBounds Attempt to index outside the
bounds of a string.
UnsupportedOperationException An unsupported operation was
encountered.
Exception Description
try-catch Blocks
try block
Java try block is used to enclose the code that might throw an exception. It must
be used within the method.
The JVM firstly checks whether the exception is handled or not. If exception is
not handled, JVM provides a default exception handler that performs the
following tasks:
Prints out exception description.
Prints the stack trace (Hierarchy of methods where the exception
occurred).
Causes the program to terminate.
System.out.println("other statement);
}catch(Exception e){System.out.println("handeled");}
System.out.println("normal flow..");
}
}
finally block
Java finally block is a block that is used to execute important code or to
put "cleanup" code such as closing connection, closing a file stream etc.
Java finally block is always executed whether exception is handled or
not.Java finally block must be followed by try or catch block.
Note: If you don't handle exception, before terminating the
program, JVM executes finally block(if any).
Rule: For each try block there can be zero or more catch blocks, but only one
finally block.
Note: The finally block will not be executed if program exits(either by calling
System.exit() or by causing a fatal error that causes the process to abort).
throw keyword
The Java throw keyword is used to explicitly throw an exception.
We can throw either checked or uncheked exception in java by throw
keyword. The throw keyword is mainly used to throw custom exception.
We will see custom exceptions later.
The syntax of java throw keyword is given below.
throw exception;
For Example:
throw new IOException("sorry device error);
Let us see the example to manually throw the ArithmeticException
otherwise print a message welcome to vote.
public class TestThrow1{
static void validate(int age){
if(age<18)
throw new ArithmeticException("not valid");
else
System.out.println("welcome to vote");
}
public static void main(String args[]){
validate(13);
System.out.println("rest of the code...");
}
}
Output:
Exception in thread main java.lang.ArithmeticException:not valid
throws keyword
The Java throws keyword is used to declare an exception. It gives an
information to the programmer that there may occur an exception so it is
better for the programmer to provide the exception handling code so that
normal flow can be maintained.
Exception Handling is mainly used to handle the checked exceptions. If
there occurs any unchecked exception such as NullPointerException, it is
programmers fault that he is not performing check up before the code
being used.
Let's see the example of java throws clause which describes that checked
exceptions can be propagated by throws keyword.
import java.io.IOException;
class Testthrows1{
void m()throws IOException{
throw new IOException("device error");//checked exception }
void n()throws IOException{
m();
}
void p(){
try{
n();
}catch(Exception e){System.out.println("exception handled");}
}
public static void main(String args[]){
Testthrows1 obj=new Testthrows1();
obj.p();
System.out.println("normal flow...");
}
}
Output:
exception handled
normal flow...
Exceptions Methods:
Following is the list of important medthods available in the Throwable class.
SN Methods with Description
Withdrawing $600...
Sorry, but you are short $200.0
InsufficientFundsException
at CheckingAccount.withdraw(CheckingAccount.java:25)
at BankDemo.main(BankDemo.java:13)
All the operations that you perform on a data such as searching, sorting,
insertion, manipulation, deletion etc. can be performed by Java Collections.
Java Collection simply means a single unit of objects. Java Collection framework
provides many interfaces (Set, List, Queue, Deque etc.) and classes (ArrayList,
Vector, LinkedList, PriorityQueue, HashSet, LinkedHashSet, TreeSet etc).
SN Interfaces with Description
1 The Collection Interface
This enables you to work with groups of objects; it is at the top of the
collections hierarchy.
2 The List Interface
This extends Collection and an instance of List stores an ordered
collection of elements.
3 The Set
This extends Collection to handle sets, which must contain unique
elements
4 The SortedSet
This extends Set to handle sorted sets
5 The Map
This maps unique keys to values.
6 The Map.Entry
This describes an element (a key/value pair) in a map. This is an inner
class of Map.
7 The SortedMap
This extends Map so that the keys are maintained in ascending order.
8 The Enumeration
This is legacy interface and defines the methods by which you can
enumerate (obtain one at a time) the elements in a collection of objects.
This legacy interface has been superceded by Iterator.
Java ArrayList class uses a dynamic array for storing the elements.It
extends AbstractList class and implements List interface.
Java ArrayList class can contain duplicate elements.
Java ArrayList class maintains insertion order.
Java ArrayList class is non synchronized.
Java ArrayList allows random access because array works at the index
basis.
In Java ArrayList class, manipulation is slow because a lot of shifting
needs to be occurred if any element is removed from the array list.
Creating ArrayList object:
ArrayList al=new ArrayList();//creating old non-generic arraylist
OR
ArrayList<String> al=new ArrayList<String>();
//creating new generic arraylist
Example of Java ArrayList class:
import java.util.*;
class TestCollection1{
public static void main(String args[]){
In the above example, we have seen traversing ArrayList by Iterator. Let's see the
example to traverse ArrayList elements using for-each loop.
Iterating the elements of Collection by for-each loop
import java.util.*;
class TestCollection2{
public static void main(String args[]){
ArrayList<String> al=new ArrayList<String>();
al.add("value1");
al.add("value2");
al.add("value3");
al.add("value4");
for(String obj:al)
System.out.println(obj);
}
}
Output: value1
value2
value3
value4
import java.util.*;
Iterator itr=al.iterator();
al.removeAll(al2);
Iterator itr=al.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
}
}
}
Output:
iterating the elements after removing the elements of al2...
Vijay
Ajay
al.retainAll(al2);
Iterator itr=al.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
}
}
}
Output:
Ravi
ArrayList LinkedList
1) ArrayList internally LinkedList internally uses doubly linked
uses dynamic array to store the list to store the elements.
elements.
2) Manipulation with ArrayList Manipulation with LinkedList is fasterthan
is slow because it internall ArrayList because it uses doubly linked list
y uses array. If any element is so no bit shifting is required in memory.
removed from the array, all the
bits are shifted in memory.
3) ArrayList class can act as a LinkedList class can act as a list and
list only because it implements queue both because it implements List and
List only. Deque interfaces.
4) ArrayList is better for storing LinkedList is better for manipulatingdata.
and accessingdata.
The Set interface contains only methods inherited from Collection and adds the
restriction that duplicate elements are prohibited.
Set also adds a stronger contract on the behavior of the equals and hashCode
operations, allowing Set instances to be compared meaningfully even if their
implementation types differ.
The methods declared by Set are summarized in the following table:
SN Methods with Description
1 add( )
Adds an object to the collection
2 clear( )
Removes all objects from the collection
3 contains( )
Returns true if a specified object is an element within the
collection
4 isEmpty( )
Returns true if the collection has no elements
5 iterator( )
Returns an Iterator object for the collection which may be used
to retrieve an object
6 remove( )
Removes a specified object from the collection
7 size( )
Returns the number of elements in the collection
Example:
Set have its implementation in various classes like HashSet, TreeSet,
LinkedHashSet. Following is the example to explain Set functionality:
import java.util.*;
HashSet class
uses hashtable to store the elements.It extends AbstractSet class and
implements Set interface.
contains unique elements only.
Output:Ajay
Vijay
Ravi
Output:WINTER
SPRING
SUMMER
FALL
Output:WINTER 5
SPRING 10
SUMMER 15
FALL 20
switch(day){
case SUNDAY:
System.out.println("sunday");
break;
case MONDAY:
System.out.println("monday");
break;
default:
System.out.println("other day");
}
}
}
Output:monday
Java Iterator
The easiest way to display each element is to use an iterator, which is an object
that implements either the Iterator or the ListIterator interface.
Iterator enables you to cycle through a collection, obtaining or removing
elements. ListIterator extends Iterator to allow bidirectional traversal of a list,
and the modification of elements.
For collections that implement List, you can also obtain an iterator by calling
ListIterator.
We will create our own custom class and make it implement Iterable, so
that it returns an Iterator using which we can iterate the elements.
import java.util.ArrayList;
import java.util.Iterator;
@Override
public boolean hasNext() {
if (position < animal.size())
return true;
else
return false;
}
@Override
public Object next() {
Object aniObj = animal.get(position);
position++;
return aniObj;
}
@Override
public void remove() {
animal.remove(position);
}
}
package com.javapapers;
import java.util.ArrayList;
import java.util.Iterator;
@Override
public Iterator<String> iterator() {
return new AnimalIterator(this);
}
import java.util.ArrayList;