You are on page 1of 6

Thr

owandThr
ows

Thr
ow-
 Thethrowkey word 
isusedtocr eateourownExcepti
onobjectandhandov
erittoJVM
manually.
 Iti
susedf orcustom except
ion.
 Aft
erthrowst at
ement ,wecan’ttakeanyotherst
atementasitwil
lbecomeunreachabl
e.

Exampl
e:
 thr
ownewI
nsuf
fi
cient
FundExcept
ion(
);

Thr
ows-

Throwskeywor
d i
susedt
odeclaret
heexcept
ionwi
thmethod.
I
tisusedtodelegat
etheresponsi
bil
i
tyofexcept
ionhandli
ngt
othecal
l
ermet
hod.Then
cal
l
ermet
hodi
sresponsi
blet
ohandl
ethatexcept
ion.

Not
e:
 Hencet hemainobj ect
iveof"thr
ows"key wor dist odelegat
etheresponsi
bil
i
tyof
excepti
onhandlingt ot
hecallermet hod.
 "t
hrows"keywordr equir
edonlyf orcheckedexcept i
ons.Usageofthrowsfor
uncheckedexceptionthereisnouse.
 "t
hrows"keywordr equir
edonlyt oconvincecompl i
er.Usageofthrowskeyword
doesn'tprev
entabnor malterminationoft hepr ogram.
 Hencer ecommendedt ouset ry
-catchov erthrowskey wor
d.
 Wecanuset hr
owskey wordonlyforconst ruct
or sandmet hodsbutnotfor
cl
asses.
Exampl
e-

v
oid 
m1(
)thr
ows 
IOExcept
ion{
  

 
  
 m2(
);
  

}
 

Not
e:

Inourprogram withinthetryblock,i
fthereisnochanceofri
singanexcepti
ont henwe
can'
trightcat
chbl ockforthatexcepti
onot herwi
sewewill
getcompi l
etimeerrorsayi
ng
excepti
onXXXi snev erthr
owni nbodyofcor r
espondi
ngt
rystatement.Butt
hisrulei
s
appli
cableonl
yf orful
lycheckedexcept i
on.
Howt
ocr
eat
ethecust
om except
ioni
njav
a
Wecancr
eat
eourownExcept
iont
hati
sknownascust
om except
ionoruser
-def
inedexcept
ion.

Byt
hehel
pofcust
om except
ion,
youcanhav
eyourownexcept
ionandmessage.

Exampl
e-1-Scenar
io

Somet
imesi
tisr
equi
redt
odev
elopmeani
ngf
ulexcept
ionsbasedonappl
i
cat
ionr
equi
rement
s.

Forexampl
esupposey
ouhav
eonesav
ingsaccounti
nSBIBankandy
ouhav
e50000i
nyour

account
.Supposey
ouat
tempt
edt
owi
thdr
aw60000f
rom y
ouraccount
.Inj
avay
oucanhandl
e.

Youneedt
odi
spl
aysomeer
rormessager
elat
edt
oinsuf
fi
cientf
und.

St
epst
ocr
eat
etheuserdef
inedexcept
ion

1.Cr
eat
ethenewcl
ass.

2.Theuserdef
inedexcept
ioncl
assmustext
end

f
rom 
j
ava.
lang.
Except
ion 
or 
j
ava.
lang.
RunTi
meExcept
ion 
class.

3.Whi
l
ecr
eat
ingcust
om except
ion,
pref
ert
ocr
eat
eanunchecked,
Runt
imeexcept
iont
han

acheckedexcept
ion.

4.Ev
eryuserdef
inedexcept
ioncl
assi
nwhi
chpar
amet
ri
zedConst
ruct
ormustcal
l
ed

par
amet
ri
zedConst
ruct
orofei
ther 
j
ava.
lang.
Except
ion or
 

j
ava.
lang.
RunTi
meExcept
ion 
classbyusi
ngsuper
(st
ri
ngpar
amet
eral
way
s).

5.I
tishi
ghl
yrecommendedt
omai
ntai
nourcust
omi
zedexcept
ionsasuncheckedby

ext
endi
ngRunt
imeExcept
ion.Wecancat
chanyThr
owabl
ety
pei
ncl
udi
ngEr
ror
sal
so.

packagecom.
vel
oci
ty;

publ
iccl
assI
nsuf
fi
cient
FundExcept
ionext
endsRunt
imeExcept
ion{

pr
ivat
eSt
ri
ngmessage;

publ
icI
nsuf
fi
cient
FundExcept
ion(
Str
ingmessage){
//t
his.
message=message;
super(
message)
;
}
}

packagecom.
vel
oci
ty;

publ
iccl
assAccount{

pr
ivat
eintbal
ance=3000;

publ
ici
ntbalance(
){
r
etur
nbalance;
}

publi
cvoidwi
thdraw(i
ntamount){
i
f(amount>balance){
t
hrownewI nsuf
fi
cient
FundExcept
ion(
"I
nsuf
fi
cientbal
ancei
nyour
account.
."
);
}
bal
ance=balance-amount;
}
}

packagecom.
vel
oci
ty;

publ
iccl
assMai
nTest{

publ
icst
ati
cvoi
dmai
n(St
ri
ng[
]ar
gs){

Accountaccount=newAccount();
Syst out
em. .pr
int
ln(
"Curr
entbal
ance:"+account
.bal
ance(
));
account
.wit
hdraw(3500);
Syst out
em. .pr
int
ln(
"Curr
entbal
ance:"+account
.bal
ance(
));
}
}
Exampl
e-2

packagecom.
test
;

cl
assTestext
endsExcept
ion{

publ
icTest(
Stri
ngs){
super(
s);
}

packagecom.
test
;

publ
iccl
assTest
1{

publ
icst
ati
cvoi
dmai
n(St
ri
ng[
]ar
gs){

t
ry{

thrownewTest (
"I
nval
i
dinput
");
}cat
ch( Except
ione){
e.getMessage(
);
}
}
}

Quest
ion.
 Whati
sthedi
ff
erenceBet
weenCat
chandFi
nal
l
yinj
ava?

Sr
. Cat
ch Fi
nal
l
y
No.
1 Cat
chbl
ockhandl
est
heer
rorwheni
toccur
sint
rybl
ock Ther eisnoneedofexceptionthrownby
tryblock
2 Cat
chbl
ockisexecut edonlywhent hei
fexcepti
onisthrown Finall
yblockisalwaysexecutedwhether
byt
rybl
ock,other
wi seiti
snotexecuted exceptionoccursornot
3 Wecanusemul ti
plecatchblockforonl
yonet r
yblock Onl yonefi
nall
yblockisusedf oronetr
y
block
4 Wecanhandlemul t
ipleexcepti
onsbyusingcatchblocks Itisnotforexcepti
onhandling
Q.1

i
ntm1( ){
tr
y{
r
eturn10;
}catch(Except
ione){
r
eturn20;
}fi
nally{
r
eturn30;
}
}

r
etur
n-30

Event houghretur
nstatementpresenti
ntryorcatchblocksf i
rstf
inal
lywi
llbeexecut
edand
afterthatonl
yreturnst
atementwillbeconsi
dered.i
.efinall
yblockdominatesret
urnstat
ement
.
Ifreturnst
atementpresenttr
y,catchandfi
nal
lyblockst henfi
nall
yblockretur
n
statementwi l
lbeconsider
ed

Q2

publicclassFinal
lyTest{
i
ntm1( ){
try{
return10;
}cat ch(Excepti
one){
return20;
}finall
y{
return30;
}
return40;
}
}

I
twi
l
lnotcompi
l
e,unr
eachabl
ecoder
etur
n40.

Sel
fAssi
gnment
:

Whati
sthedi
ff
erencebet
weenCheckedExcept
ionandUncheckedExcept
ionkey
wor
d?

Whati
sthedi
ff
erencebet
weent
hrowandt
hrows?

Whati
str
ywi
thr
esour
ces?(
ver
sion1.
7onwar
ds)

Whati
smul
ti
plecat
chbl
ock(
ver
sion1.
7onwar
ds)
Not
e:

Whil
eoverri
dingifthechildcl
assmet hodthr
owsanycheckedexcepti
on
compul
sorythepar entclassmethodshouldthrowthesamecheckedexcept
ionori
ts
par
entother
wi sewewi l
lgetcompi l
etimeerror.
Butt
herearenor estr
ict
ionsforun-checkedexcept
ions.

Case Val
id/I
nval
id
1)Par
ent:publ
icv
oidmet
hodOne(
)thr
owsExcept
ion Val
i
d
Chi
ld :publ
icv
oidmet
hodOne(
)
2)Par
ent:publ
icv
oidmet
hodOne(
) I
nval
i
d
Chi
ld :publ
icv
oidmet
hodOne(
)thr
owsExcept
ion
3)Par
ent:publ
icv
oidmet
hodOne(
)thr
owsExcept
ion Val
i
d
Chi
ld :publ
icv
oidmet
hodOne(
)thr
owsExcept
ion
4)Par
ent:publ
icv
oidmet
hodOne(
)thr
owsI
OExcept
ion I
nval
i
d
Chi
ld :publ i
cv oi
dmethodOne(
)throwsExcepti
on
5)Parent:publicvoi
dmethodOne()t
hrowsIOException Val
i
d
Chi
ld :publ i
cv oi
dmethodOne(
)throwsEOFExcept i
on,Fil
eNotFoundExcepti
on
6)Parent:publicvoi
dmethodOne()t
hrowsIOException I
nval
i
d
Chi
ld :publ i
cv oi
dmethodOne(
)throwsEOFExcept i
on,Int
erruept
edExcepti
on
7)Parent:publicvoi
dmethodOne()t
hrowsIOException Val
i
d
Chi
ld :publ i
cv oi
dmethodOne(
)throwsEOFExcept i
on,Ari
thematicExcept
ion
8)Parent:publicvoi
dmethodOne() Val
i
d
Chi
ld :publ i
cv oi
dmethodOne(
)throwsNull
PointerExcepti
on,
Ari
themat
icExcepti
on,
Runti
meException

You might also like