电子商务毕业论文外文翻译范文《Thinking In Java》Word下载.docx
《电子商务毕业论文外文翻译范文《Thinking In Java》Word下载.docx》由会员分享,可在线阅读,更多相关《电子商务毕业论文外文翻译范文《Thinking In Java》Word下载.docx(12页珍藏版)》请在冰点文库上搜索。
surprisingly,theywouldn’tcheckfortheerrorconditions(andsometimestheerrorconditionsweretoosillytocheckfor).Ifyouwerethoroughenoughtocheckforanerroreverytimeyoucalledamethod,yourcodecouldturnintoanunreadablenightmare.Becauseprogrammerscouldstillcoaxsystemsoutoftheselanguages,theywereresistanttoadmittingthetruth:
thatthisapproachtohandlingerrorswasamajorlimitationtocreatinglarge,robust,maintainableprograms.
Thesolutionistotakethecasualnatureoutoferrorhandlingandtoenforceformality.Thisactuallyhasalonghistory,becauseimplementationsofexceptionhandlinggobacktooperatingsystemsinthe1960s,andeventoBASIC’s“onerrorgoto.”ButC++exceptionhandlingwasbasedonAda,andJava’sisbasedprimarilyonC++(althoughitlooksmorelikethatinObjectPascal).
Theword“exception”ismeantinthesenseof“Itakeexceptiontothat.”Atthepointwheretheproblemoccurs,youmightnotknowwhattodowithit,butyoudoknowthatyoucan’tjustcontinueonmerrily;
youmuststop,andsomebody,somewhere,mustfigureoutwhattodo.Butyoudon’thaveenoughinformationinthecurrentcontexttofixtheproblem.Soyouhandtheproblemouttoahighercontextwheresomeoneisqualifiedtomaketheproperdecision(muchlikeachainofcommand).
Theotherrathersignificantbenefitofexceptionsisthattheycleanup
1
errorhandlingcode.Insteadofcheckingforaparticularerroranddealingwithitatmultipleplacesinyourprogram,younolongerneedtocheckatthepointofthemethodcall(sincetheexceptionwillguaranteethatsomeonecatchesit).And,youneedtohandletheprobleminonlyoneplace,theso-calledexceptionhandler.Thissavesyoucode,anditseparatesthecodethatdescribeswhatyouwanttodofromthecodethatisexecutedwhenthingsgoawry.Ingeneral,reading,writing,anddebuggingcodebecomesmuchclearerwithexceptionsthanwhenusingtheoldwayoferrorhandling.
BecauseexceptionhandlingistheonlyofficialwaythatJavareportserrors,anditisenforcedbytheJavacompiler,thereareonlysomanyexamplesthatcanbewritteninthisbookwithoutlearningaboutexceptionhandling.Thischapterintroducesyoutothecodeyouneedtowritetoproperlyhandleexceptions,andthewayyoucangenerateyourownexceptionsifoneofyourmethodsgetsintotrouble.
1.Basicexceptions
Anexceptionalconditionisaproblemthatpreventsthecontinuationofthemethodorscopethatyou’rein.It’simportanttodistinguishanexceptionalconditionfromanormalproblem,inwhichyouhaveenoughinformationinthecurrentcontexttosomehowcopewiththedifficulty.Withanexceptionalcondition,youcannotcontinueprocessingbecauseyoudon’thavethe
informationnecessarytodealwiththeprobleminthecurrentcontext.Allyoucandoisjumpoutofthecurrentcontextandrelegatethatproblemtoahighercontext.Thisiswhathappenswhenyouthrowanexception.
Divisionisasimpleexample.Ifyou’reabouttodividebyzero,it’sworthcheckingforthatcondition.Butwhatdoesitmeanthatthedenominatoriszero?
Maybeyouknow,inthecontextoftheproblemyou’retryingtosolveinthat
particularmethod,howtodealwithazerodenominator.Butifit’sanunexpectedvalue,youcan’tdealwithitandsomustthrowanexceptionratherthancontinuingalongthatexecutionpath.
Whenyouthrowanexception,severalthingshappen.First,theexceptionobjectiscreatedinthesamewaythatanyJavaobjectiscreated:
ontheheap,withnew.Thenthecurrentpathofexecution(theoneyoucouldn’tcontinue)isstoppedandthereferencefortheexceptionobjectisejectedfromthecurrentcontext.Atthispointtheexceptionhandlingmechanismtakesoverandbeginstolookforanappropriateplacetocontinueexecutingtheprogram.This
2
appropriateplaceistheexceptionhandler,whosejobistorecoverfromtheproblemsotheprogramcaneithertryanothertackorjustcontinue.
Asasimpleexampleofthrowinganexception,consideranobjectreferencecalledt.It’spossiblethatyoumightbepassedareferencethathasn’tbeeninitialized,soyoumightwanttocheckbeforetryingtocallamethodusingthatobjectreference.Youcansendinformationabouttheerrorintoalargercontextbycreatinganobjectrepresentingyourinformationand“throwing”itoutofyourcurrentcontext.Thisiscalledthrowinganexception.
1.1Exceptionarguments
LikeanyobjectinJava,youalwayscreateexceptionsontheheapusingnew,whichallocatesstorageandcallsaconstructor.Therearetwoconstructorsinallstandardexceptions;
Thefirstisthedefaultconstructor,andthesecondtakesastringargumentsoyoucanplacepertinentinformationintheexception:
thrownewNullPointerException("
t=null"
);
Thisstringcanlaterbeextractedusingvariousmethods,asyou’llsee.
Thekeywordthrowcausesanumberofrelativelymagicalthingstohappen.Typically,you’llfirstusenewtocreateanobjectthatrepresentstheerrorcondition.Yougivetheresultingreferencetothrow.Theobjectis,ineffect,“returned”fromthemethod,eventhoughthatobjecttypeisn’tnormallywhatthemethodisdesignedtoreturn.Asimplisticwaytothinkaboutexceptionhandlingisasadifferentkindofreturnmechanism,althoughyougetintotroubleifyoutakethatanalogytoofar.Youcanalsoexitfromordinaryscopesbythrowinganexception.Butavalueisreturned,andthemethodorscopeexits.
Anysimilaritytoanordinaryreturnfromamethodendshere,becausewhereyoureturnissomeplacecompletelydifferentfromwhereyoureturnforanormalmethodcall.(Youendupinanappropriateexceptionhandlerthatmightbefar—manylevelsawayonthecallstack—fromwheretheexceptionwasthrown.)
Inaddition,youcanthrowanytypeofThrowable(theexceptionrootclass)objectthatyouwant.Typically,you’llthrowadifferentclassofexceptionforeachdifferenttypeoferror.Theinformationabouttheerrorisrepresentedbothinsidetheexceptionobjectandimplicitlyinthenameoftheexceptionclass,sosomeoneinthebiggercontextcanfigureoutwhattodowithyourexception.(Often,theonlyinformationisthetypeofexception,andnothingmeaningfulisstoredwithintheexceptionobject.)
2.Catchinganexception
3
Ifamethodthrowsanexception,itmustassumethatexceptionwillbe“caught”anddealtwith.Oneoftheadvantagesofexceptionhandlingisthatitallowsyoutoconcentrateontheproblemyou’retryingtosolveinoneplace,andthendealwiththeerrorsfromthatcodeinanotherplace.
Toseehowanexceptioniscaught,youmustfirstunderstandtheconceptofaguardedregion.Thisisasectionofcodethatmightproduceexceptionsandisfollowedbythecodetohandlethoseexceptions.
2.1Thetryblock
Ifyou’reinsideamethodandyouthrowanexception(oranothermethodyoucallwithinthismethodthrowsanexception),thatmethodwillexitintheprocessofthrowing.Ifyoudon’twantathrowtoexitthemethod,youcanset
upaspecialblockwithinthatmethodtocapturetheexception.Thisiscalledthetryblockbecauseyou“try”yourvariousmethodcallsthere.Thetryblock
isanordinaryscopeprecededbythekeywordtry:
try{
//Codethatmightgenerateexceptions
}
Ifyouwerecheckingforerrorscarefullyinaprogramminglanguagethatdidn’tsupportexceptionhandling,you’dhavetosurroundeverymethodcallwithsetupanderrortestingcode,evenifyoucallthesamemethodseveraltimes.Withexceptionhandling,youputeverythinginatryblockandcapturealltheexceptionsinoneplace.Thismeansyourcodeismucheasiertowriteandreadbecausethegoalofthecodeisnotconfusedwiththeerrorchecking.
2.2Exceptionhandlers
Ofcourse,thethrownexceptionmustendupsomeplace.This“place”istheexceptionhandler,andthere’soneforeveryexceptiontypeyouwanttocatch.Exceptionhandlersimmediatelyfollowthetryblockandaredenotedbythekeywordcatch:
}catch(Type1id1){
//HandleexceptionsofType1
}catch(Type2id2){
//HandleexceptionsofType2
}catch(Type3id3){
4
//HandleexceptionsofType3
//etc...
Eachcatchclause(exceptionhandler)islikealittlemethodthattakesoneandonlyoneargumentofaparticulartype.Theidentifier(id1,id2,andsoon)canbeusedinsidethehandler,justlikeamethodargument.Sometimesyouneverusetheidentifierbecausethetypeoftheexceptiongivesyouenoughinformationtodealwiththeexception,buttheidentifiermuststillbethere.
Thehandlersmustappeardirectlyafter