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

Exception in Java (5)

Uploaded by

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

Exception in Java (5)

Uploaded by

parveenbegam377
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 26

Exception:-

Exception is an unexpected event which occur during execution of program


In java we have two kinds of flow of execution
1)normal flow
2)exception flow
NORMAL FLOW:-
In normal flow program starts checks for abnormal statement
if abnormal statement is not present execution continue &starts normally &we
get complete output
EXCEPTION FLOW:-
Execution of program start and check for abnormal statement if abnormal
statement present execution occurs
control checks for exception is not handles execution stop fill fully &we get
partial output

Check
Abnormal
statement Exception
Present/not

Exception Handled
Continue
or not

Completed Stop fullfully

Complete Output Partial output


Exception are classified into two types
1)check exception
2)uncheck exception
Check exception:-
Exception which are known to the compiler are known as check exception
It is mandatory to handle check exception else we get compile time error

Uncheck exception :-
Exception which are not known to the compiler are known as uncheck
exception
It is not mandatory to handle uncheck exception

EXCEPTION HIERARCHY:-
Whenever exception occur a throwable type object will be created which will be
having reason &stack trace of the exception

THROWABLE

ERROR EXCEPTION

Ex:-out of Memory Error


Stackoverflow Error
Runtime Problem COMPILE TIME EXCEPTION
RUNTIME EXCEPTION (CHECKED EXCEPTION
(UNCHECKED EXCEPTION 1)Filenot found exception
1)Arithemetic Exception 2)IO Exception
2)Null pointer Exception 3)SQL Exception
3)Classcast Exception 4)Interupted Exception
What is the difference between Error and Exception
ERROR EXCEPTION

It is runtime problem caused by It is runtime problem caused by code


system resource sortage
We cannot recovery error We can handle exception

It is classified as uncheck error It is classified as check


Eg;- exception&uncheck exception
Stackoverflow error Ex:-
Arithmetic exception

Ex for check exception:-


Package exception;
Public class p1
{
P s v m(s[]args)
{
P1 obj=new p1();
P1 obj=(p1)obj.clone();//clonemotsupportedexception
}}

Package exception;
Public class p2
{
P s v m(s[]args)
{
Thread.sleep(1000);//interepted exception
}}

Ex for uncheck exception:-


Package exception;
Public class p1
{
int i=10;
P s v m(s[]args)
{
s.o.pln(10/0);//arithmetic exception
p1 obj=null;
s.o.pln(obj.i);
}
}
Note:-
Exceptions are handled in following ways
1)using try and catch block
2)using throws
Try &catch block:-
Syntax:-
try{
//abnormal stmt
}
Catch(throwable type ref)
{
//stmt
}
Try and catch block is used to handle both check exception as well as uncheck
exception
Try &catch block must be created together (Ie)
We can’t have catch block without try block
Catch block will be executed only when exception will caught
import java.util.Scanner;
public class Main
{
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
try
{
System.out.println("welcome to app");
System.out.println("enter the 1st number");
int a=sc.nextInt();
System.out.println("Enter the 2st number");
int b=sc.nextInt();
System.out.println(a/b);
System.out.println("thank you for using the app");}
catch(ArithmeticException e)
{
System.out.println("zero not aloowed.....");
}
}
}
SYNTAX:-
Try{
//Abnormal stmt
}
Catch (throwable type ref){
//stmt
}
Catch (throwable type ref){
//stmt
}
Only one block will be executed exception object propagates from top to
bottom order
So we must design multiple catch block in such a way catch block with
sub class must be in the first place and catch block with the super class must be
at the bottom else we get compile time error.
public class Main
{
int i=10;

public static void main(String [] args){


try {
System.out.println("welcome to app");
System.out.println(10/0);
Main obj=null;
System.out.println(obj.i);
System.out.println("thank you using app");
}
catch(NullPointerException e)
{
System.out.println("object not created");
}
catch(Exception e){
System.out.println("zero not allowed.....");
}
}
}

FINALLY BLOCK:-
Finally block is used to execute mandatory statements in java
Finally block will be executed in following situation.
1. Exception not accur.
2. Exception accur not handled
3. Exception accur and it is handled
We can have finally block in following situation.
Try with finally try&catch with finally try&multiple catch with finally
Try try try
{ { {
} } }
Finally catch( ) catch( )
{ { {
} } }
Finally catch( )
{ {
} }
Finally
{
}
Package exception
Public class p1
{
Public `static void main (string [ ] args)
{
try
{
S.O.Pln(“welcome to app”);
S.O.Pln(“10/10”);
}
Catch(arithmeticexception e)
{
S.O.Pln(“zero not allowed:…!”);
}
Finally
{
S.O.Pln(“Thank for using App”);
}
}
Using throw keywords:-
Throws is the keywords which is used to declare the exception.
Throws must be used with method declaration only.
If a check exception is not handle using try& catch block it must be
declared using throw.
If the called method is throwing an exception calling method must
handle(or) declare same exception.
If the super class method is throwing an exception than the sub class over
riding method must also declare same exception (or) its super class.
We can throw n-number of exception .
SYNTAX:-

[modifier] return type methodname((FA)) throwsE1, E2, E3,….. En,

{
//stmt
}
package deepika;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;

public class exception {

public static void main(String[] args) throws


FileNotFoundException {
System.out.println("main begin");
ram();

}
public static void ram()throws
FileNotFoundException {
System.out.println("ram begin");
sita();
System.out.println("ram end");
}
public static void sita()throws
FileNotFoundException{
System.out.println("sita begin");
FileOutputStream out = new FileOutputStream("C:\\
java\\demo.text");

System.out.println("sita end");
}
}
Custom Exception:-
Exception created by the user are known as user defined exception (or)
custom exception.
We can create custom exception using throw keyword .
Steps to crete custom exception .
Step1:-
Create a class and extend to end any of the exception class.
Step2:-
Create a class Exception object using throw keywords.
Note:-
If the created class Extending to check than it is behaves like checked
Exception .
If the created class is extending to unchecked exception then is behaves
liked checked Exeption

package encapsulation;

public class salaryexception extends RuntimeException


{

}
class employee
{
int eid;
String ename;
double sal;
public employee(int id,String ename,double
sal)
{
this.eid=eid;
this.ename=ename;
if(sal<0)
{
throw new salaryexception();
}
else
{
this.sal=sal;
}}}
class testemployee
{
public static void main(String[] args) {
employee e1=new
employee(1,"smith",10.25);
THROW THROWS
It is used to stop the execution of
program and create an except object It is used to declar the exceptions

Throw can be inside block Throws must be used with method


declaration

We can create only one exception We can declar n number of exception


object at atime

System.out.println(e1);}

collection
Collection framework is a set of classes, interface, which provides mechanism
to store and manipulate group of objects
In collection we can achieve all the operations that you perform on a data such
as searching, sorting ,insertion ,manipulation and deletion etc…
Using collection framework we can store only objects (non primitive types).we
cannot store primitive types. If we try to store primitive types ,it will be
implicitly converted to non-primitive types(auto boxing)

In collection framework we have many heirarchies


1)collection hierarchy
2)map hierarchy
Collection Interface
Collection is an interface which is present in java utill package
The collection interface is the interface which is implemented by
all the classes in the collection framework. It declares the methods
the every collection will have methods of collection interface.

SNO PURPOSE RETURN METHOD SIGNATURE


TYPE
1 Add an element 1.add (object o)
2.addall (collection c)
2 Searching an 1.contains (object o)
element 2.contains all (collection c)
3 Remove an 1.remove (object o)
element 2.removeall (collection c)
3.retain all (collection c)
4.clear ()
4 Access element 1.interator ()
2.we can access with the
help of for each loop
5 Miscellaneous 1.size ()
2.isempty ()
3.toarray ()
4.hashcode ()
5.equals ()

Sub interfaces of collection interface


1.list -for array index
2.queuefirst in first out
3.setto avoid duplicate value

PARAMETER LIST QUEUE SET

Insertion order maintained Follows Depends on


First in first out implementation
duplicate allowed Allowed Not allowed

index yes No no
retrieval 1.iterator 1.iterator() 1.iterator()
2.listiterator 2.foreach 2.foreach()
3.foreach
Implementing 1.arraylist 1.priority queue 1.hashset
class 2.linkedlist 2.Array deque 2.treeset
3.vector 3.linkedhashset
4.stack

List Interface:-
List interface is the child interface of collection interface
It inhibits a list type data structure in which we can store the ordered
collection of objects
It can have duplicate values
It also provides methods like
s.no purpose Method signature
1. Add an element 1.add(int index, object o)
2.addall(int index ,collection c)
2. Searching an element Index of (object o)

3. Remove element Remove (int index)

4. Access element 1.listiterator()


2.get(int index)
List interface is implemented by the classes
 Arraylist
 Linkedlist
 Vector
 Stack
ARRAYLIST:-
The arraylist class implements the list interface
It uses adynamic array to store the duplicate element of different
data types
The arraylist class maintaines the insertion order
It is non synchronized
It is not threadsafe.
The elements stored in the array list class can be randomly accessed
so retrieval is fast
To add the elements to the arraylist
To add the elements
1)add(objects)
a1.add(40);
a1.add(20);
a1.add(10);
a1.add(30);
ArrayList a12=new ArrayList();
a12.add(50);
a12.add(60);
System.out.println(a12);
2)to all (collection)
A1.addall(a12);
System.out.println(a1);//[40,20,10,30,50,60]
System.out.println(a1.size());//6
System.out.println(a1.contains(50));//true
Add(object)
A1.add(12);
System.out.println(a1);
System.out.println(a1.size());
System.out.println(a1.contains(50));

TO REMOVE THE ELEMENTS TO THE ARRAYLIST


package deepika;

import java.util.ArrayList;
public class p2 {
public static void main(String[] args) {
ArrayList a1=new ArrayList();
a1.add(40);
a1.add(20);
a1.add(10);
a1.add(30);
System.out.println(a1);
//remove object
a1.remove(Integer.valueOf(20));
System.out.println(a1);
//remove (index int)
a1.remove(1);
System.out.println(a1);
}
}
ITERATOR LISTITERATOR

Iterator()present in List iterator()present in list


iterator interface iterator is sub interface of
iterator interface
Iterator() returns List iterator()present in list
iterator type object iterator type object
Iterator is used to List iterator is used traverse
traverse list, set ,and only list
map
Iterator is used to List Iterator is used to traverse
traverse collection only collection both forward and
in forward direction backword direction
We can perform only remove We can perform add, remove and set
operation while traversing operation while traversing

Note:
In the iterator when we try to access an element using only next() and
if there is no element present.
Then we get NosuchElementException
1)using iterator()
Iterator i=a1.iterator();
While(i.hasnext())
{
System.out.println(i.next()+” ,”);
}
i.next();//nosuchelementexception
2)using listiterator()
Listiterator is=a1.listiterator(a1.size());
While(is.hasprevious())
{
System.out.println(is.prevoius()+”,”);
3)using the for each loop
For(object o:a1)
{
System.out.println(o+”,”);
}
4)using get(index)
System.out.println(a1.get(2));

Note:
Collection can be classified into two types.
1.non-Generic collection
2.Generic collection
Parameter Non – Generic Generic collection
collection
Syntax Arraylist List=new Arraylist<ReferenceType>
Arraylist() list=new
Arraylist<ReferenceType>()
Elements Heterogenous Homogeneous elements
elements
Retrieval Individual type No typecasting is needed
casting needs to bo
done at every
retrieved
Compile – Time Checked for type Checked for type safety at
Checking safety at runtime compile time
Note :

Comparable Interface Comparator Interface


Comparable interface present in Comparator interface present in
java.lang.package java.lang.package
Sort the elements according to
Sort the elements according to customized
natural sorting order and only one
sorting order and multiple property
property
Comparable interface has compare
Comparator interface has compare()
To()
Comparable affects the original Compactor does not affects the original
class class
Syntax to sort:
Syntax to sort:
Collection.sort(list.comparator)
Collection.sort(list)
We can sort collection using sort methods of collection class, They
are

1.sort(reference)
2.sort(reference, comparator type object)
import java.util.*;
public class p1
{
public static void main(String[] args)
{
List<String> sList = new ArrayList<String>();
sList.add("s");
sList.add("u");
sList.add("r");
sList.add("y");
sList.add("a");
Collections.sort(sList); //sorts array list
for(String str: sList)
System.out.print(" "+str);
}
}

Linked List:
 LinkedList implements the collection interface
 It user doubly linked list internally to store the elements
 It can store the duplicate elements
 It maintains the insertion order.
 It is not synchronized.
 In Linkedlist the manipulation is fast because no shifting is
required.

Vector:
Vector uses a dynamic array to store the data elements.
It is synchronized and contains many methods that are not the part of
collection framework.
It is a thread safe
It is similar to arraylist but is slow when compared to arraylist.
Stack :
The stack is the subclass of vector
It implements the last-in-first-out data structure
The stack contains all of the methods of vector class and also provides
its methods like
1. Push(object)add objects
2. Pop()to remove objects
3. Peek()to see top objects

Queue Interface:
The interface queue is available in the java.util.package
It is used to keep the elements that are processed in the First in First
out(FIFO) manner.
It is an ordered list of objects, where insertion of elements occurs at
the end of the list, and removal of elements occur at the beginning of
the list.
Implementing classes,
 ArrayDeque
 PiriorityQueue
 LinkedList
Implementations done by these classes are not thread safe. It is
required to have a thread safe implementation class below class is an
available option.
1. PirorityBlockingQueue

Method Description
Booleanoffer(object) It is used to insert the specified
element into this queue.
Object remove() It is used to retrieves and removes the
head of this queue.
Object poll() It is used to retrieves and removes the
head of this queue, or returns null if
this queue is empty.
Object element() It is used to retrieves but does not
remove the head of this queue.
Object peek() It is used to retrieves, but does not
remove the head of this queue, or
returns null if this queue is empty.

Priority Queue Class:


It is implementing class of queue interface.
The insertion and deletion of objects follows FIFO pattern.
However, sometimes the elements of the queue are needed to be
processed according to the priority, that’s where a priority queue
comes into action.
import java.util.*;
public class p1
{
public static void main(String[] args)
{
ArrayDeque<Integer>ad=new ArrayDeque<>();

ad.offer(20);
ad.offer(30);
ad.offer(10);
ad.offer(40);
System.out.println(ad);
while(!ad.isEmpty())
{
System.out.print(ad.poll()+",");
}
System.out.println();
PriorityQueue<Integer>pq=new PriorityQueue<>();
pq.offer(20);
pq.offer(30);
pq.offer(10);
pq.offer(40);
System.out.println(pq);
while(!pq.isEmpty());
{
System.out.print(pq.poll()+",");
}
}
}

Set interface:
The set interface is present in java.util.package
It is an unordered collection of objects.
Duplicates values cannot be stored .
This interface contains the methods inherited from the collections
interface and adds a feature that restricts the insertion of the duplicate
elements.
Implementing classes
 HashSet
 Linked HashSet
 TreeSet
Hashset:
Implements set interface.
The underlying data structure for hashset is Hashtable.
As it implements the set interface duplicate values are not allowed.
Object that you insert in hashset are not guaranteed to be inserted in
the same order objects are inserted based on their hash code.
NULL elements are allowed in hashset.
Hashset also implements serializable and doneable interfaces.
Linked Hashset:
Duplicate value are not allowed
Null elements are allowed in linked Hashset.
It is non- synchronized
It maintains insertion order.

Treeset:
Duplicate values are not allowed
Elements are sorted by default in ascending order.
Null elements are not allowed in treeset
It is non – synchronized
We can sort the elements in customized order using comparator.
import java.util.*;
public class p1
{

public static void main(String[] args)


{
HashSet<Integer>hs=new HashSet<>();

hs.add(20);
hs.add(40);
hs.add(10);
hs.add(30);

System.out.println(hs);
TreeSet<Integer>ts=new TreeSet<>();
ts.add(20);
ts.add(40);
ts.add(10);
ts.add(30);
System.out.println(ts);
for(int n:ts)
System.out.print(n+",");
System.out.println();
Iterator<Integer>l=ts.descendingIterator();
while(l.hasNext())
{
System.out.print(l.next()+",");
}
}
}

Map:
The map interface is present in java.util.package
Map contains values on the basic of key, ie,key and value pair. Each
key and value pair is known as an entry.
Map doesn’t allow duplicate keys, but you can have duplicate values.
Map is useful if you have to search , update or delete elements on the
basics of a key.
Map can’t be traversed, so you need to convert it into set using key
set() or entry set() method.
You cannot store duplicate keys, however if you try to store duplicate
key with another value , it will replace the value.
Implementing classes of map interface
o Hashmap
o LinkedHashmap
o Treemap
o Hashtable
Method of map Interface
S.NO Method signature Purpose
1 Put(key,value) Add an entry to the map
Replace the add value with new
value of an existing entry in the
map.
2 Put All(Map) Copies all the entries from the
given map into current map
3 Contains Key(key) Check whether the key is present
or not and returns Boolean value.
4 Contains Value(value) Checks whether the value is
present or not and returns Boolean
value.
5 Remove(key) If the key is present entry is
removed from the map and the
value is returned
If the key is not present nothing is
removed and null is returned
6 Clear() It removes all the entries in the
map.
7 Get(key) It return the value for the specified
key from the map, if the key is not
present it will return null.
8 Isempty() To check whether the map has
mappings or not. The return type
of this method is Boolean.
9 Values() It returns a collection of values
present in the map collection <v>.
10 Key set() It returns a set of keys present in
the map return type set <key>
11 Entry set() It returns a set of the entries
present in the map return type is
set <key, value>
12 Size() It returns the size or number of
entries inside the map.

HashMap:
It contains only unique keys
It may have one null keyand multiple null values
It is non- synchronized
It maintains no order.

Linked HashMap:
It contains unique elements
It may have one null key and multiple null values
It is non- synchronized
It maintains insertion order
TreeMap:
it contains only unique elements
it cannot have a null key but can have multiple null values
it is non synchronized
it maintains ascending order
Hashtable:
It contains unique elements
It doesn’t allow null key or value
It is synchronized.

import java.util.*;
public class p1
{
public static void main(String[] args)
{
HashMap<Integer,String>hm=new HashMap<>();

hm.put(1, "sheela");
hm.put(2,"leela");
hm.put(3,"laila");
hm.put(4,"mala");
System.out.println(hm);
//to search key
System.out.println(hm.containsKey(3));
//to search value
System.out.println(hm.containsValue("mala"));
//to get the value using key
System.out.println(hm.get(3));
//to iterate keys
Set<Integer>keys=hm.keySet();
Iterator I1=keys.iterator();
while(I1.hasNext());
{
System.out.print(I1.next()+",");
}
System.out.println();
//to iterate values
Collection<String>values=hm.values();
Iterator I2=values.iterator();
while(I2.hasNext())
{
System.out.print(I2.next()+",");
}

//to iterate entry


Set entry=hm.entrySet();
Iterator e=entry.iterator();
while(e.hasNext())
{
System.out.println(e.next());
}
} }

You might also like