Exceptions in JavaWord文档下载推荐.docx
- 文档编号:20043978
- 上传时间:2023-01-16
- 格式:DOCX
- 页数:27
- 大小:63.47KB
Exceptions in JavaWord文档下载推荐.docx
《Exceptions in JavaWord文档下载推荐.docx》由会员分享,可在线阅读,更多相关《Exceptions in JavaWord文档下载推荐.docx(27页珍藏版)》请在冰豆网上搜索。
thandleitself,itmaythrowanexception.Throwinganexceptionislikethrowingabeeping,flashingredballtoindicatethereisaproblemthatcan'
tbehandledwhereitoccurred.Somewhere,youhope,thisballwillbecaughtandtheproblemwillbedealtwith.Exceptionsarecaughtbyhandlerspositionedalongthethread'
smethodinvocationstack.Ifthecallingmethodisn'
tpreparedtocatchtheexception,itthrowstheexceptionuptoitscallingmethod,andsoon.Ifoneofthethreadsofyourprogramthrowsanexceptionthatisn'
tcaughtbyanymethodalongthemethodinvocationstack,thatthreadwillexpire.WhenyouprograminJava,youmustpositioncatchers(theexceptionhandlers)strategically,soyourprogramwillcatchandhandleallexceptionsfromwhichyouwantyourprogramtorecover.
Exceptionclasses
InJava,exceptionsareobjects.Whenyouthrowanexception,youthrowanobject.Youcan'
tthrowjustanyobjectasanexception,however--onlythoseobjectswhoseclassesdescendfromThrowable.Throwableservesasthebaseclassforanentirefamilyofclasses,declaredinjava.lang,thatyourprogramcaninstantiateandthrow.Asmallpartofthisfamilyisshownin
图表1ApartialviewoftheThrowablefamily
AsyoucanseeinFigure1,Throwablehastwodirectsubclasses,ExceptionandError.Exceptions(membersoftheExceptionfamily)arethrowntosignalabnormalconditionsthatcanoftenbehandledbysomecatcher,thoughit'
spossibletheymaynotbecaughtandthereforecouldresultinadeadthread.Errors(membersoftheErrorfamily)areusuallythrownformoreseriousproblems,suchasOutOfMemoryError,thatmaynotbesoeasytohandle.Ingeneral,codeyouwriteshouldthrowonlyexceptions,noterrors.ErrorsareusuallythrownbythemethodsoftheJavaAPI,orbytheJavavirtualmachineitself.
Inadditiontothrowingobjectswhoseclassesaredeclaredinjava.lang,youcanthrowobjectsofyourowndesign.Tocreateyourownclassofthrowableobjects,youneedonlydeclareitasasubclassofsomememberoftheThrowablefamily.Ingeneral,however,thethrowableclassesyoudefineshouldextendclassException.Theyshouldbe"
exceptions."
Thereasoningbehindthisrulewillbeexplainedlaterinthisarticle.
Whetheryouuseanexistingexceptionclassfromjava.langorcreateoneofyourowndependsuponthesituation.Insomecases,aclassfromjava.langwilldojustfine.Forexample,ifoneofyourmethodsisinvokedwithaninvalidargument,youcouldthrowIllegalArgumentException,asubclassofRuntimeExceptioninjava.lang.
Othertimes,however,youwillwanttoconveymoreinformationabouttheabnormalconditionthanaclassfromjava.langwillallow.Usually,theclassoftheexceptionobjectitselfindicatesthetypeofabnormalconditionthatwasencountered.Forexample,ifathrownexceptionobjecthasclassIllegalArgumentException,thatindicatessomeonepassedanillegalargumenttoamethod.Sometimesyouwillwanttoindicatethatamethodencounteredanabnormalconditionthatisn'
trepresentedbyaclassintheThrowablefamilyofjava.lang.
Asanexample,imagineyouarewritingaJavaprogramthatsimulatesacustomerofavirtualcafé
drinkingacupofcoffee.Considertheexceptionalconditionsthatmightoccurwhilethecustomersips.TheclasshierarchyofexceptionsshowninFigure2representsafewpossibilities.
Figure2.Exceptionhierarchyforcoffeesipping
Ifthecustomerdiscovers,withdismay,thatthecoffeeiscold,yourprogramcouldthrowaTooColdException.Ontheotherhand,ifthecustomerdiscoversthatthecoffeeisoverlyhot,yourprogramcouldthrowaTooHotException.Theseconditionscouldbeexceptionsbecausetheyare(hopefully)notthenormalsituationinyourcafé
.(Exceptionalconditionsarenotnecessarilyrare,justoutsidethenormalflowofevents.)Thecodeforyournewexceptionclassesmightlooklikethis:
//InSourcePacketinfileexcept/ex1/TemperatureException.java
classTemperatureExceptionextendsException{
}
//InSourcePacketinfileexcept/ex1/TooColdException.java
classTooColdExceptionextendsTemperatureException{
//InSourcePacketinfileexcept/ex1/TooHotException.java
classTooHotExceptionextendsTemperatureException{
Thisfamilyofclasses,theTemperatureExceptionfamily,declaresthreenewtypesofexceptionsforyourprogramtothrow.Notethateachexceptionindicatesbyitsclassthekindofabnormalconditionthatwouldcauseittobethrown:
TemperatureExceptionindicatessomekindofproblemwithtemperature;
TooColdExceptionindicatessomethingwastoocold;
andTooHotExceptionindicatessomethingwastoohot.NotealsothatTemperatureExceptionextendsException--notThrowable,Error,oranyotherclassdeclaredinjava.lang.
Throwingexceptions
Tothrowanexception,yousimplyusethethrowkeywordwithanobjectreference,asin:
thrownewTooColdException();
ThetypeofthereferencemustbeThrowableoroneofitssubclasses.
Thefollowingcodeshowshowaclassthatrepresentsthecustomer,classVirtualPerson,mightthrowexceptionsifthecoffeedidn'
tmeetthecustomer'
stemperaturepreferences.NotethatJavaalsohasathrowskeywordinadditiontothethrowkeyword.Onlythrowcanbeusedtothrowanexception.Themeaningofthrowswillbeexplainedlaterinthisarticle.
//InSourcePacketinfileexcept/ex1/VirtualPerson.java
classVirtualPerson{
privatestaticfinalinttooCold=65;
privatestaticfinalinttooHot=85;
publicvoiddrinkCoffee(CoffeeCupcup)throws
TooColdException,TooHotException{
inttemperature=cup.getTemperature();
if(temperature<
=tooCold){
thrownewTooColdException();
}
elseif(temperature>
=tooHot){
thrownewTooHotException();
//...
//InSourcePacketinfileexcept/ex1/CoffeeCup.java
classCoffeeCup{
//75degreesCelsius:
thebesttemperatureforcoffee
privateinttemperature=75;
publicvoidsetTemperature(intval){
temperature=val;
publicintgetTemperature(){
returntemperature;
Catchingexceptions
TocatchanexceptioninJava,youwriteatryblockwithoneormorecatchclauses.Eachcatchclausespecifiesoneexceptiontypethatitispreparedtohandle.Thetryblockplacesafencearoundabitofcodethatisunderthewatchfuleyeoftheassociatedcatchers.Ifthebitofcodedelimitedbythetryblockthrowsanexception,theassociatedcatchclauseswillbeexaminedbytheJavavirtualmachine.Ifthevirtualmachinefindsacatchclausethatispreparedtohandlethethrownexception,theprogramcontinuesexecutionstartingwiththefirststatementofthatcatchclause.
Asanexample,consideraprogramthatrequiresoneargumentonthecommandline,astringthatcanbeparsedintoaninteger.WhenyouhaveaStringandwantanint,youcaninvoketheparseInt()methodoftheIntegerclass.Ifthestringyoupassrepresentsaninteger,parseInt()willreturnthevalue.Ifthestringdoesn'
trepresentaninteger,parseInt()throwsNumberFormatException.Hereishowyoumightparseanintfromacommand-lineargument:
//InSourcePacketinfileexcept/ex1/Example1.java
classExample1{
publicstaticvoidmain(String[]args){
inttemperature=0;
if(args.length>
0){
try{
temperature=Integer.parseInt(args[0]);
catch(NumberFormatExceptione){
System.out.println(
"
Mustenterintegerasfirstargument."
);
return;
else{
Mustentertemperatureasfirstargument."
//Createanewcoffeecupandsetthetemperatureof
//itscoffee.
CoffeeCupcup=newCoffeeCup();
cup.setTemperature(temperature);
//Createandserveavirtualcustomer.
VirtualPersoncust=newVirtualPerson();
VirtualCafe.serveCustomer(cust,cup);
Here,theinvocationofparseInt()sitsinsideatryblock.AttachedtothetryblockisacatchclausethatcatchesNumberFormatException:
catch(NumberFormatExceptione){
Thelowercasecharactereisareferencetothethrown(andcaught)NumberFormatExceptionobject.Thisreferencecouldhavebeenusedinsidethecatchclause,althoughinthiscaseitisn'
t.(Examplesofcatchclausesthatusethereferenceareshownlaterinthisarticle.)
IftheusertypesHarumphasthefirstargumenttotheExample1program,parseInt()willthrowaNumberFormatExceptionexceptionandthecatchclausewillcatchit.Theprogramwillprint:
Mustenterintegerasfirstargument.
Althoughtheaboveexamplehadonlyonecatchclause,youcanhavemanycatchclausesassociatedwithasingletryblock.Here'
sanexample:
//InSourcePacketinfileexcept/ex1/VirtualCafe.java
classVirtualCafe{
publicstaticvoidserveCustomer(VirtualPersoncust,
CoffeeCupcup){
cust.drinkCoffee(cup);
System.out.println("
Coffeeisjustright."
- 配套讲稿:
如PPT文件的首页显示word图标,表示该PPT已包含配套word讲稿。双击word图标可打开word文档。
- 特殊限制:
部分文档作品中含有的国旗、国徽等图片,仅作为作品整体效果示例展示,禁止商用。设计者仅对作品中独创性部分享有著作权。
- 关 键 词:
- Exceptions in Java
![提示](https://static.bdocx.com/images/bang_tan.gif)