电子商务毕业论文外文翻译范文《Thinking In Java》.docx
- 文档编号:4052407
- 上传时间:2023-05-06
- 格式:DOCX
- 页数:12
- 大小:23.88KB
电子商务毕业论文外文翻译范文《Thinking In Java》.docx
《电子商务毕业论文外文翻译范文《Thinking In Java》.docx》由会员分享,可在线阅读,更多相关《电子商务毕业论文外文翻译范文《Thinking In Java》.docx(12页珍藏版)》请在冰点文库上搜索。
电子商务毕业论文外文翻译范文《ThinkingInJava》
电子商务毕业论文外文翻译范文《ThinkingInJava》
ThinkingInJava
ThebasicphilosophyofJavaisthat“badlyformedcodewillnotberun.”
Theidealtimetocatchanerrorisatcompiletime,beforeyoueventrytoruntheprogram.However,notallerrorscanbedetectedatcompiletime.Therestoftheproblemsmustbehandledatruntimethroughsomeformalitythatallowstheoriginatoroftheerrortopassappropriateinformationtoarecipientwhowillknowhowtohandlethedifficultyproperly.
Candotherearlierlanguagesoftenhadmultipleerror-handlingschemes,andtheseweregenerallyestablishedbyconventionandnotaspartoftheprogramminglanguage.Typically,youreturnedaspecialvalueorsetaflag,andtherecipientwassupposedtolookatthevalueortheflaganddeterminethatsomethingwasamiss.However,astheyearspassed,itwasdiscoveredthatprogrammerswhousealibrarytendtothinkofthemselvesasinvincible—asin,
“Yes,errorsmighthappentoothers,butnotinmycode.”So,nottoo
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:
try{
//Codethatmightgenerateexceptions
}catch(Type1id1){
//HandleexceptionsofType1
}catch(Type2id2){
//HandleexceptionsofType2
}catch(Type3id3){
4
//HandleexceptionsofType3
}
//etc...
Eachcatchclause(exceptionhandler)islikealittlemethodthattakesoneandonlyoneargumentofaparticulartype.Theidentifier(id1,id2,andsoon)canbeusedinsidethehandler,justlikeamethodargument.Sometimesyouneverusetheidentifierbecausethetypeoftheexceptiongivesyouenoughinformationtodealwiththeexception,buttheidentifiermuststillbethere.
Thehandlersmustappeardirectlyafter
- 配套讲稿:
如PPT文件的首页显示word图标,表示该PPT已包含配套word讲稿。双击word图标可打开word文档。
- 特殊限制:
部分文档作品中含有的国旗、国徽等图片,仅作为作品整体效果示例展示,禁止商用。设计者仅对作品中独创性部分享有著作权。
- 关 键 词:
- Thinking In Java 电子商务毕业论文外文翻译范文Thinking In Java 电子商务 毕业论文 外文 翻译 范文 Thinking Java