0% found this document useful (0 votes)
61 views49 pages

8 - Exception Handling, Collection

Exception Handling describes what exceptions are, how they are thrown and handled, and the different types of exceptions including checked exceptions, runtime exceptions, and errors. It explains how exceptions propagate through the call stack and how exception handlers are used to catch exceptions. Finally, it provides examples of exception handling code using try, catch, finally, and throws keywords.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
61 views49 pages

8 - Exception Handling, Collection

Exception Handling describes what exceptions are, how they are thrown and handled, and the different types of exceptions including checked exceptions, runtime exceptions, and errors. It explains how exceptions propagate through the call stack and how exception handlers are used to catch exceptions. Finally, it provides examples of exception handling code using try, catch, finally, and throws keywords.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 49

Exception Handling

What is an Exception?
• It’s an abnormal condition that occurs during the execution of a
program, & due to which the normal flow of the program's
instructions may disrupt.

For example:-
class Test{
public static void main(String[] args){
System.out.println(5/0);
System.out.println("Hello");
// do something else
}
}
Guess the output…
Exception in thread "main" java.lang.ArithmeticException: / by zero
at NewClass.main(NewClass.java:20)
Throwing an exception
• When an error occurs within a method, the run-time
system creates an object and hands it off to the method.
The object, called an exception object, contains
information about the error, including its type and the state
of the program when the error occurred. Creating an
exception object and handing it to the relevant method is
called throwing an exception.

• After a method throws an exception, the runtime system


attempts to find the ordered list of methods that had been
called to get to the method where the error occurred. The
list of methods is known as the call stack.
Understanding the Call Stack
y(), where exception occurred Class Test
{
public static void main(String[]
args)
{ new Test().x(); }
x() void x()
{ y(); }
void y()
{ int a = 7/0; }
}
main()

Exception in thread "main" java.lang.ArithmeticException: / by zero


at NewClass.y(NewClass.java:23)
at NewClass.x(NewClass.java:21)
at NewClass.main(NewClass.java:19)
Exception Handler
The runtime system searches the call stack for a method
that contains a block of code that can handle the
exception. This block of code is called an exception
handler.

 The search begins with the method in which the error


occurred and proceeds through the call stack in the
reverse order in which the methods were called.

When an appropriate handler is found, the runtime


system passes the exception object to the handler.

 An exception handler is considered appropriate if the


type of the exception object thrown matches the type that
can be handled by the handler.
Searching for the Exception Handler in the
Call Stack
throws exception y(), where exception occurred Looking for appropriate handler

should handle but Looking for appropriate handler


may forward x()
exception

should handle but


may forward exception main()

If main forwarded the exception, the thread will abnormally terminate.


Catch or Specify Requirements
• The code that might throw certain exception must be
enclosed either by :
• A try statement that catches the exception. The try must provide a
handler for the exception.
• A method that specifies that it can throw the exception. The method
must provide a throws clause that lists the exception.

• Code that fails to honor the Catch or Specify requirement


will not compile.

• Not all exceptions are subject to the Catch or Specify


requirement.
Exception Types

• Checked Exception

• Run-time Exception
Unchecked Exception
• Error
Class Hierarchy

java.lang.Object

java.lang.Throwable

java.lang.Error java.lang.Exception

java.lang.RuntimeException
Checked Exception
• An exceptional condition that a well-written application
should anticipate and recover from. For example:-
• java.io.FileNotFoundException
• Java.io.IOException
• Java.io.InterruptedException

• Checked exceptions are subject to the Catch or Specify


Requirement.

• All exceptions are checked exceptions, except for those


indicated by Error, RuntimeException, and their
subclasses.
Runtime Exception
Exceptional conditions that are internal to the application,
and that the application usually cannot anticipate.

Usually indicate programming bugs, such as logic errors


or improper use of an API.
Runtime exceptions are not subject to the Catch or
Specify requirement. Runtime exceptions are those
indicated by RuntimeException and its subclasses.
Ex :-
 java.lang.NullPointerException
 java.lang.ArrayIndexOutOfBoundsException
 java.lang.ArithmeticException
Error
• Exceptional conditions that are external to the application,
and that the application usually cannot anticipate.

• Ex :- java.io.IOError

• Errors are not subject to the Catch or Specify Requirement.

• Errors are those exceptions indicated by Error and its


subclasses.
Runtime Exception due to Logical Errors
public class NewClass
{
public static void main(String[] args)
{
int array[] = {6,7,8,9,10};
for(int index=0; index<array.length+2; index++)
System.out.print(array[index]+” “);
System.out.println("After loop");
}
}
Guess the output:-
6 7 8 9 10
Exception in thread "main"java.lang.ArrayIndexOutOfBoundsException:
5 at NewClass.main(NewClass.java:22)
Runtime Exception contd.
public class NewClass
{
public static void main(String[] args)
{
System.out.println("1st statement");
show(null);
System.out.println("3rd Statement");
}
static void show(String msg)
{
System.out.println(msg.toUpperCase());
}
}
Guess the output:-
1st statement
Exception in thread "main" java.lang.NullPointerException at
NewClass.main(NewClass.java:21)
Using finally Block
try{
System.out.println(9/0);
System.out.println("Hello");
}
catch(Exception e){
System.out.println(e.getMessage());
}
finally{
System.out.println("2nd Last statement");
}
System.out.println("Last statement");
Class Hierarchy

java.lang.Object

ArrayIndexOutOfBoundsException

java.lang.Throwable

StringIndexOutOfBoundsException
java.lang.Exception

IndexOutOfBoundsException
java.lang.RuntimeException
int arr[] = {5,6,7};
try{
System.out.println(arr[5]);
}
catch(Exception e)
{
System.out.println("first catch");
}
catch(RuntimeException re)
{
System.out.println("2nd catch");
}
public static void main(String[] args) {
System.out.println(m());
}
static int m() {
try {
int x = 7/0;
return x;
}
catch(Exception e) {
System.out.println("catch block");
return 0;
}
finally {
System.out.println("finally block");
return 1;
}
}
Handling Checked Exception
public static void main(String[] args) throws FileNotFoundException
{
try{
m();
}
catch(IOException e)
{ //….. }
}
static void m() throws FileNotFoundException
{
try{
FileInputStream fis = new FileInputStream("abc.java");
}
catch(FileNotFoundException
e)
{ //….. }
}
Keywords For Exception Handling:
• try
• catch
• finally
• throws
• throw

20
Collection Framework
Supported By : java.util package
Introduction
 Collections Framework provides a well-designed set of interfaces
and classes for storing and manipulating groups of data as a single
unit, a collection.

 It provides a convenient API to many of the ADTs like maps, sets,


lists, trees, arrays, hash tables, and other collections.

 It provides a standard programming interface to many of the most


common abstractions, without burdening the programmer with too
many procedures and interfaces.

 Due to Object-oriented design, the classes in the Framework


encapsulate both the data structures and the algorithms associated
with the ADTs.
Interface Hierarchy
java.lang.Iterable<E>
java.lang.Iterable<E>

java.util.Map<E>
java.util.Map<E>
java.util.Collection<E>
java.util.Collection<E>

java.util.SortedMap<E>
java.util.SortedMap<E>
java.util.List<E> java.util.Set<E>
java.util.Set<E>
java.util.List<E>

java.util.Queue<E> java.util.NavigableMap<E>
java.util.NavigableMap<E>
java.util.Queue<E>
Added in Java SE 6
java.util.SortedSet<E>
java.util.SortedSet<E>
Added in Java SE 6
java.util.Deque<E>
java.util.Deque<E>
java.util.NavigableSet<E>
java.util.NavigableSet<E>
Added in Java SE 6
java.util.Collection<E>
• Super Interface for all classes that define a collection.

• Defines the most fundamental behavior of every collection object.

• Because Collection extends Iterable all collections can be cycled


through using for-each loop.
public interface java.lang.Iterable{
java.util.Iterable<E> public abstract java.util.Iterator iterator();
java.util.Iterable<E>
}

public interface java.util.Iterator{


java.util.Collection<E>
java.util.Collection<E> public abstract boolean hasNext();
public abstract java.lang.Object next();
public abstract void remove();
}
java.util.Collection<E> contd.
int size()

boolean isEmpty()

boolean contains(Object obj)

Iterator iterator()

Object[] toArray()

boolean add(Object obj)

boolean remove(Object)
java.util.Collection<E> contd.
boolean containsAll(Collection c)

boolean addAll(Collection c)

boolean removeAll(Collection c)

boolean retainAll(Collection c)

void clear( )

boolean equals(Object obj)


java.util.List<E>
• Declares the behavior of a collection that stores a
sequence of elements.
• Elements can be inserted or accessed by their position in
the list.
• It may have duplicate elements & null also.

java.util.Iterable<E>
java.util.Iterable<E>

java.util.Collection<E>
java.util.Collection<E>

java.util.List<E>
java.util.List<E>
java.util.List<E> contd.
ListIterator listIterator()

ListIterator listIterator(int index)


Iterator starting from index.

Object remove(int)

Object set(int)

List subList(int start,int end)


java.util.ArrayList<E>
Java.lang.Object
Java.lang.Object

Collection<E>
Collection<E>

AbstractCollection<E>
AbstractCollection<E>

List<E>
List<E>

AbstractList<E>
AbstractList<E>

ArrayList<E>
ArrayList<E>

Other Interfaces Implemented by ArrayList : java.util.RandomAccess


java.lang.Cloneable
java.io.Serializable
java.util.Iterator<E>
boolean hasNext();
Object next();
void remove();

java.util.ListIterator<E> extends java.util.Iterator<E>

boolean hasNext();
Object next();
boolean hasPrevious();
Object previous();
int nextIndex();
int previousIndex();
void remove();
void add(Object);
Using for-each style for loop
ArrayList names = new ArrayList();
names.add("John");
names.add("Brad");
names.add("Smith");
for(Object name:names){
// your code goes here
}
Set<E> extends Collection<E>
 Declares the behavior of a Set. i.e., a Collection that doesn’t allow
duplicate elements.

 add() returns false if we try to insert duplicate elements to the set.

 Doesn’t declare any method of its own.


SortedSet<E> extends Set<E>
 Declares the behavior of a set sorted in ascending order.

 E first()
HashSet<E> & TreeSet<E>
Java.lang.Object
Java.lang.Object

AbstractCollection<E>
AbstractCollection<E>

Set<E>
Set<E> AbstractSet<E> NavigableSet<E>
NavigableSet<E>
AbstractSet<E>

HashSet<E>
HashSet<E> TreeSet<E>
TreeSet<E>
Using TreeSet<E>
TreeSet countries = new TreeSet();
countries.add("India");
countries.add("America");
countries.add("France");
countries.add("London");
countries.add("Russia");
countries.add("China");

System.out.println(countries);

Output : [America, China, France, India, London, Russia]


Map<K,V>
Stores Key-Value pairs.
Both keys and values are objects.
Keys are unique but values may be duplicated.
Map doesn’t extends Iterable.

• void clear( )

• boolean containsKey(Object k)

• boolean containsValue(Object v)

• Set<Map.Entry<K,V>> entrySet( )

• V get(Object key)
 boolean isEmpty( ) Map<K,V> contd.

 Set<K> keySet( )

 V put(K,V)
Adds a key-value pair. Overwrites any previous value associated with the
key. Returns null if key didn’t already exist. Otherwise previous value with the
key is returned.

 void putAll( Map<? extends K, ? extends V> m )

 V remove(Object key)

 int size( )

 Collection<V> values( )
HashMap<K,V> & TreeMap<K,V>
Map<K,V>
Map<K,V>
Java.lang.Object
Java.lang.Object

SortedMap<K,V>
SortedMap<K,V>

AbstractMap<K,V>
AbstractMap<K,V>

NavigableMap<K,V>
NavigableMap<K,V>

HashMap<K,V>
HashMap<K,V> TreeMap<K,V>
TreeMap<K,V>
HashMap<K,V>
 Uses HashTable to store the map.
 The insertion and retrieval time is independent of the size of the map.

Constructors
HashMap()

public static void main(String[] args) {


HashMap hm = new HashMap();
hm.put(101,"Sohan");
hm.put(102,"John");
hm.put(103,"Vimal");
hm.put(104,"Sunil");

Set<Map.Entry> set = hm.entrySet();


for( Map.Entry me : set )
System.out.println("Room No. : "+me.getKey()+" is booked for
"+me.getValue() );
}
Wrapper Classes for Primitives
Primitive Wrappers

• Provides a way of wrapping primitive values in an


object so that a primitive can be treated as an
object.

• Provides a set of utility methods for primitives.


Situations when required
• When primitives are required to be added to a collection
object.

• When we want to return a primitive from a method that


returns an object.

• When converting primitives to and from String objects.

• When converting primitives & String objects to and from


different bases like binary, octal & hexadecimal.
Wrapper Classes
Creating Objects
Integer i1 = new Integer(5);
Integer i2 = new Integer(“5”);

Float f1 = new Float(5.6f);


Float f2 = new Float(“5.6f”);

Double d1 = new Double(6.7);


Double d2 = new Double(“6.7”);

Character c = new Character(‘a’);

Boolean b1 = new Boolean(true);


Boolean b2 = new Boolean(“true”);
Boolean b3 = new Boolean(“TrUe”);
Creating Objects contd.

valueOf() methods

Integer i1 = Integer.valueOf(“101”,2);
Integer i2 = Integer.valueOf(“F”,16);
Integer i3 = Integer.valueOf(“012”,8);
Integer i4 = Integer.valueOf(“102”);
Class Hierarchy
java.lang.Object

java.lang.Number
java.lang.Character

java.lang.Byte
java.lang.Boolean

java.lang.Short

java.lang.Float java.lang.Integer

java.lang.Double java.lang.Long
java.lang.Number
public java.lang.Number();
java.lang.Object

public abstract int intValue();

public abstract long longValue();


java.io.Serializable
public abstract float floatValue();

public abstract double doubleValue();

public byte byteValue(); java.lang.Number

public short shortValue();


Wrapper Conversion Utilities contd.
Integer i = new Integer(200);
byte b = i.byteValue(); Stack
short s = i.shortValue();
long l = i.longValue();
b
float fl = i.floatValue(); f1
s Heap
l
Float f = new Float(5.6f);
byte b2 = f.byteValue(); b2 200
short s2 = f.shortValue(); s2
5.6
int i2 = f.intValue();
i2 i

f
Boxing & Unboxing

• Integer ref = new Integer(15);


Encapsulating the primitive value in the respective
Wrapper object is called boxing or Wrapping.

• int a = ref.intValue() + 5;
Getting the encapsulated value out of the object is
called unboxing or unwrapping.
AutoBoxing & AutoUnboxing
Supported by jdk1.5+

• Integer i = 67;
automatically translated into following code by the compiler.
Integer i = new Integer(67); // so called AutoBoxing

• int a = i + 10;
automatically translated into following code by the compiler.
int a = i.intValue() + 10; // so called AutoUnboxing

You might also like