0% found this document useful (0 votes)
29 views14 pages

Java Unit 4 R23

Uploaded by

maneeshgopisetty
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
29 views14 pages

Java Unit 4 R23

Uploaded by

maneeshgopisetty
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 14

<br> <br>

andling unit-4 JMocels af xe plion Handlhg


Exton chater-2 models of Exce ton Handlt,
Java Contains
Exeian Rondling
tsbornnifyosts4 I: Terminalion model
Itoduction 2 Resumption model
stand ard Ereptien dasses
2-2:Hicrarchy
|ot f throw tr catch and {tnally
3: keyuords thross and ) Termination mohe rrosih
Mutiple catch clause ovns
In a method
the Termination model when
S. classThrowoble.
en ceunter
3:ypes o
Excegtios Erce ption exte ptionfurther gocessing ih that
6• Unchecked an
1: checeed Exceptions
ot methl Terminded and the
tronsfeted to the heare st
catch block.
Exeption:
a
Exce plion is an abroftmalCodition
abnorrmal Itis Resamption
mel:.
Yontime The Excegion handler tries to relity he
eIror.
ma
excepton situaten ond esume he
the program
abnormal event that
An erceçtion is an
og(atm, H
o CCur during te,. executgnof Hiecorchy
tstandad Exce plion classes
Extegtin Honding
hdis used lobject)
kordlny 4 mechanišm
ass howable
Throw aile
btohondli fun time eYorsw
EKerlion
Subclass

not Joand LEsror


lass [Run tme Ercegtion
datementitoit.Io Extejstton Excerteon

SQLEKte tion
Exteptòn
vitual Linfeag cass Cost Ex cetlon
Machine Erroß
Error Memor9
Error bArraystoretxce ptbn >nterupEx ce rte
uncheceed ExLe btton herta Erefo
<br> <br>

In jalan Excetions aYe inetonce of classes, derive&


Progam
from the clase tho wable, which in turn is derived t
class hi
Jiom the Lass 'objed.
}un(sting orgrl3)
2- Java Exce ption Hierarchy inherted by twosub clacses
int az6,beor C;
i-e Exception, Error trg
Types of Exception :
SoPln blbck)
cas s sub divided
the sub class ot Exteptton afe
into Aooo
tyes (i m)
cateh (ArthmetiExceton
Ichecked Exce ption
2- uncheeed Eregtion

Unchec Fed Exception (Runtitme Exce plon):


onler Exceptfon Handling Techniques
An exce
tnht cannotbeaight ba (od Reywofds

but it 0cCurs at the time of progam exe


cuton
jasa oudes exte pten
is calledr unchected oexcestion Ther hecfes Reya xdu for handling

at Runtime These are detied fom, jaang: tg


2-Cstth
ge- Aithmelic Exception NulPointerbxeptiony'a Exce
tthe
AayJndebutQ BoundEreption }2
2 checked Excertion Blopk
checked by the" cónpiler
An exceptien ht is chec ked
Compilation is calle d
othe ime of
ecived fom java-lang-EK«e ptn
4featech (Exce pl bnl ohjl
Exceptun.
Theee F le NotoundEkietion,
NasuchMethad I Exe te try blo (ode 1 |.Execute cach Block

e: AascN &foundExcepion,
No Exeption attheExce ton ob)
Ercelan, Exeytibn,MjaceExeptan thouw KuExeeoe catch lock

Finglly cath(Exepion obj


uExecaie fnally \WExecute cath Blak
<br> <br>

2. catch{ibloc k:
I state ment
mentgtht ttavi ked to cath the exeption
I
catch block is
atch (EKegton ob
thrown by the ty block
the bxeptiug matte
dil staement,i that sHdles the exeption tine if it
chec
ksnith
catch ) it eXe cute the cich Bock.
S xcepion type is not match at the frst
catch block one by ore
catch bler t,t check the
the ther
Finally
L
statement
Sytar:. cath( Exce ption ob)
Hondles the Excepton
statemnt that
Bloce :
tryí)
|: The try bl ock is used to checkthe
3: finallyt
totenet for exte ptfon:
(ode s placed n
ty bock to (- The final bok is aluoays exeted
27he s
createan exceionwhich follouedby mtter whether
uhether.there s exce t'on or not

2
Catch to
blocknto hand le
hand le the Exception,1t an
2-The final Beckr is optonal
f the eretion OCcurs in try block, it thows
3 for block be e
toto
eoch' they Can only
the eKepton cateh bloct

Sytax
to perform ceanup opet ons ike
connec ton
clazing afile clocing Sockel, losing database
Ilstotement that cause
int a C33= toreoso )
an Exteytisn a CioJ=l0; S- when bypaced by
the are

statements Such Continuer break tetuvn


cachEXeeyleon as
catch(Attay Oatof Sourd Exeten
isttemet tht hadles Suntex fally
the Eneytoo s0PAn"hil; +hidi
Ilsidtement
<br> <br>

class Hello
Threu Feyuoré is
| The -

hr
pablic stele void main (string args{ 3) exce ption txplicitly.e cass
en ereegt
2: It passes the obj ct of
catch Jock.
to ch
So-PAn" I am try bloce " Freetir
3
we either or unctec ked
Can throw
by using 4hrow (keywor
catch(Aiamelec ExcepionaMt
tho the, acetton,
Jormally the try bece
. theo the
finly
Seppose wantto eyuck.
isu always exeeted exce ptien the usercan use thro
S'oln(Finally Bock
S we Can't throw he maltiple cxeptons

Syrtax
2
class Excelion Ex ceptton ClassNamel
tho
ex:- throuw new Arithmetictxeption);

Pregran
int i= 6j=o,k,le;
try )class ThiuE xomrge

Enteredtg pabdic static void main(Stingargs)

throw Aithmetie ExepliongThswExcetòn


Jinally new

int k=il2; catchArithmete Erceptin ;


so-PANle); (or) so-pAn
(e-getecsage)

33
<br> <br>

Throw EXample 2 Throws(


) class
meheds
Peywold isLsed,A in
is
pudie statre voi hail | The Thíows)
exception that
he tyye of
2: I4 declares
mehod.
try
mig OCar wtth in the: cing
exceptione
Hai 3· We mkrle
throwx new NallYointer Exeeptfen (" Can
thro
Gateh(Nall P oint er Fxe ptton "ne) Reywore
used to
Throws

checked Exceytions

psum (strin aget1)


þublie uoid method name () throws Fxebtton clascName
hail bodtfsri
39
regcam
class howEomples
class Throws Exoml
statie void eligibility ((nt age)
þu blrc
pablic stotte msg() throus Anthmettc Excetion

throw new Arithmetic epton (Not valid; throw new ArthmtieExee tion (welcom
to thraw

else
Jot pablie statit oid main Ctring argdt3)

qblic stati void main (Strng try

3 catth( Arithmetic Exceptien hi)


Namaste
Soplnl
Bounds Exte ptton e)
<br> <br>

cach (Arayn dex Oul of


yMultipde
cth clauses
out ot Bounds xrept'on
s-o.Pn (AMay Index
ot uri")
try block Can ofmore
ry Hoce can ha/e
Catch clause tha means sinde cch
{
(öxce ptione)

maie cach causes. esch cateh Hock mast


SoPlnUn catehed Ekeption occurs"
Contain different oeon hndling prúlónan

Arg bock genectes only one exce ytion

at a ine e t Aine ony oneCatch 4 class Throwable wa

ock (: The Throwade


executedi lass Super class to all
is 2 is he
Syntox! the erfor and exe ptlior class
2 Throw able class is the root class af
java
exerlia handling
cateh (Exception e
) 3
he Throwale class has two subclasses
cat ch( Fxeption e
Error class 2 Exerplien clasc

dass declaration
Irogror, pablie class Throuabe
sls situ etends object implemerts
clas MultipleCtchao 2stasase3y6i Serializabe
psvn( String args
onstsuctors of class Thrunble
trg
The Five Constructors o
Je new int LsJ; he a described
int al
as
assiare
int aloJ 340;
n J: Throuabel) Tt constracts new thNowable wth n
ateh (Arthmetie Exceptton e) a
netsag
a-Throa
So-AncArthmetie eKtepttonoceurs")jsawtl able(suing me
ssSs ag)
age)>
|H Constacts throuwable
a
wth speified message
<br> <br>

Thtonae(string mesage
message,Thfouwabe Cause) exerds ar de
3' Breqar java-lang.Thieuabaà)
injort t exterds
Throwable
ŠConstucts da thrasable. with speied 8ablic clacs ThowatleFxonple
ard cause

Thíowade
qublic taie vid min (Slihg agst)
(ThowadeCause Throwable Example te new Throw able Tanple(J

with syect ied Cause


.

}
SoPAn ('Ent ered Into tdoce
5
otecied Thfowable (Sting message ThíouaHe Cause int
S-oPAn
a=
Cafa)
Bolean erabie suppession) o Fx ce
Cateh (Anthnetie tion e)
It constucts throwable iwithlspecified mesag
SoRan Exeption occured );
Cause and enable Sute ssioA.
jinally
Pethods of das Thowable wa
plonit So-fAn'The clasis:4tegetclacs(Thro bte

void add Suppessed (ThrowableExeption)s ryatyo


S:oPAn The Cause is
:te getCause Nal,]
t olr
Entered.into tyblock
2 Throuwable
fl1In stack Tracel)
9o12The class s lass jav:lan
3- Throwable get Caucel) The
The
fackage mygacag
Thhowable init Cause (Throwate ceause) Jablie cless A

sking tastringt)
l void print stack Tracel)
eam to Pack age welcome to
tstack Trace (printrensstrm)
St
SoAn welcome
'
4: Vod printStac R Trace
('printldriterpt)
javae-& A-java
java -d A
ljava
o compile
myjpacPa ge 4
<br> <br>

Cus tom Excapcion i


2 Jackage packl; ulee desined enepctin 6y
puble class
A
called Cutom Exapctin
as
iualso Custom Ertepin
e lel Can Wile
Lh tte measoges
publre oid message()s
enceptioms y tollauiy
wstiny cua tom
Exceprtiay, i
So-Pnwelcome to class A;
foStes needed to se Condsdel. u

ncepctton chis
step):-Extendto
3
chatNan
lats UseExcerin etend Gceptirn
To
javac -dA java
t
java c dB java
java pack:

3 to clase &
Stap )
Sep :- Defin tucto o
akes
useErceptin ckus
package pack; tue lcome Constiueot a

to clasA'
ingort pack\*;2nsivas
welcorne Code to lo casr,-Conaiing t
cateh ock ie
clat Ymain thaty main clals
etn wit nt he

written
am;
eatens Gcepetón
Class My Bcepclön
So-Plnelcome toi class8t
A obj s hew AO;
obj-messoge( MyEncepein(Sting str)
33
pultie ststg
setum ( The ctings -" +r1);
class UlepetinelExcepetio,
<br> <br>

cf clacc Exetion
lpsum (sting argicz) Ath mette Excertion:
y
Such as division by 2ero
bloce ); Exceptone arise S
c.o.plo (" Thiu i ty afe

My Ercerton CHai) 2. ArroyIndex Out Df Bounds Exe ptíon


thao ew used
Out of Bound inder number is
Excepctim )
Cath (my Y 3- Nal Pointertxcertion
is Cateh btock
S•opln C" This
string trenull;
s.o-Pln (e)
S-o-ln (+st;
Exce ption due to the use of object wth
noll veference
- IndexoutotBourdaFxcelion
Ercepctieng
Iyof Öut ot Bound inden number is used in arays,
stingnectors
Tyges ofExeytien
S Asay Store Exegtion

sing eng
user artay
defined f tfon Exceytion 6- cdass CatExcetion
usng ot of Bourd invalid object
checked Unchecked
INegaArgonent Excegtion

Exceptin arises due to the use


Unchecked Fxcetion
The Exetions t the time at
ogam Execution is aled unchected Exce ton: 8 alstate Excertio
in corre ct state
Ii The se:txceptiong are alcoolledruntime trceptton
2
These Exce ptlona checked.atruntime
3 The' uncheckedExceptions classes the sabelosse to negatwe ber.for the
dne 'useof humber
class ohich is
a abclas Size ot aray
<br>

<br>

lb Narnber Fotmibxtetion
Pactuges A Jase Libny
nlid Conversions to numbeS chapter-l
2- Oofining Package
3 Imprting thckageu and clascer
will arses due to itlegal operations into logams
: Poth and class Poath
<: A cCess
Conttol
checked Exceptios 6: PacEages
in java SE

found thentte
class NotFoun dExce plion:: hen class is nt $cass object
exe ption arises q:
Enumration
found then Math
2-File Not Found Ercelion: when filena s 0

{he exceyton ariieS I Wrapper classes


t2 Auto Boxing and Arto unboxing
3 clone Not Sugpated Exce ptin I3
(3 java util classes and Jnterfaces

4 TlegalAceess Exce ptioni The class not give the


petmiss ion to accesS wht is an
s. Instatition Excepton :. creating an objeet fer abstract elass
a
calle clion grp of laces, intefaes
or interface
another thed and
6-InterroedExceytin: one threod &
interrted by
7 NoSeerchield Exceytion Requestg far
8: Ro SehMelhod Exce tion
The jaua ackage usedito categorize the classes
and nterface 's It Can be caly
maintoine d.
prouides acCess
potectior

removes nonng cllis ions


<br> <br>

java- util:
Java 2

util stands
Ysigautill (ang
awt
Btfong.class : These ckage cantain s

Stannet class
stem: class * Array

- Arayl ist (lacs


csgbog
String-cla vectors
*0stacks
class *
Map:
HashtHe/ ste;etf
tinked lit
Syntar:
. clascNa re; 3 jva- io
nyert
imgert Package Subfackage.
ex: import jag util*;
all fr inpodlo pit
stonds
2-These corains
import jwa utl Scannf; e imgoring Sin8
pacageoutgols
Tyes o Packages
the strear Tepteseni,s tore the data ÄnAhe orm
.

disded tto too types ot files and also peform


int atpt task
The fateages are
u java awt
2• User- defined pacEage I- asst tor
stords abstrat windosw
tooleit tornyone nts

2-These focagehels to imgove


The APS a brary cortains dfferent tges
java is sereen
and clarLe
* courtl
paint ing

I. aa. long larg. stands tor languags. * imoges imporlant sub e


3- Tt
1- This Jackage contains langusgorted Consists
acse s a qutevent; which usetal to Jrouide
hs,
primitive typesoilwtut conpengnts Rke push buttons, radio butto
action for
steng
menuS
* EXceptiors
<br>

<br>

* Deyining acEage or)


S
javatext: rfaces
a colleciong ot e lasses, inte
t contains imgort ant classes
*Dale nfemat used for dala time fimat and subyackge
* NabeFormat use for imerie alues Regaotd þaceage
acknge A iš ceated hyusing
«ge name and
jsh:sq . and Jollouse d by the name 6f he pack
stuchose d Query language
for
stands semi
Connet to Data bace
9 These pactage helgs to Syntax

java-net ex:- pacge


net stand s for Netores:
in netoor ngoperatione Srogam
pactage myack;
er*cient Serve Jrogyamning
k Auth clas Paca ye Sample
entitaion
CommunicaRen
f puble statie void matn (Strin 4g ()
Creoting

8- jaoa- appet

Jograme kich Corne torn a


ate Package Sanple jov
Server into dient ad get erecated on the cltent b comgile javoc
PacRage Samyle
io Run - mygact.
mahine oh ehedte sejaraleubdiedry
Compiler to
tels the
class file there
1.
The
and plate the :dot
6r dab-older
encryten nd should be
Rey geneidion indicate's that
Touides a 2- The dstl:)
shdeencqption: ereted n the carent dir.
ctory
dire
<br> <br>

acess
t6access Pactage fom Anaber package ?
imyort pacage claas Mones
2

There fegram
Ao Aceess acRage fronm
are 3 ways jackage jackl;
another ac Eage publie claKA

utie uoid message


igort ekage ; a
fam class
Jackagt chsames so-lne this is atl
3}qy Quatfied Namos
ntage pacel;
importng using package namei t impoft pact-A;
Trsgtam clais

juckage ackl;
is pack fom class
dass A Soplnhs
A
objnew AO} Cernpile: javac
jubie void () 8ijava
messog)ne biev obj mess age; fatac -&

intln this is actl'fam


caa A)
System
t
3 Fally Qualified Names

jotta ge ct?; Sregarm


ingert puckage pockl;
cla ss
pabte cass A

gabkc stte wid main(Sting argl3)


palte awid thecage()
packl fem cas
A
Syctem outpinttn' This u pace 2from chyrg System at pittn This ii

objmessage()y package act2;


- A java
(ortle:javac
33 Havac -& B ava
class B
java pac2B Void mai Lstring argstD
Publtc stotte
<br>

is packe (laske');
4om elain
ncthis
A ojrew A0;
sbi-meiage

You might also like