Chapter 7 Debugging Your CodeWord格式.docx
《Chapter 7 Debugging Your CodeWord格式.docx》由会员分享,可在线阅读,更多相关《Chapter 7 Debugging Your CodeWord格式.docx(12页珍藏版)》请在冰点文库上搜索。
![Chapter 7 Debugging Your CodeWord格式.docx](https://file1.bingdoc.com/fileroot1/2023-5/6/d678896d-3660-45fa-80a2-b14babe7a42c/d678896d-3660-45fa-80a2-b14babe7a42c1.gif)
Inthischapter,we'
llseehowto
∙Startandcustomizeadebuglaunchconfiguration
∙Usedebugstackframesthatprovideexecutioncontextforvariablesanddisplayexpressions
∙Setbreakpointsandstepthroughprogramexecution
∙Inspectandchangevaluesoffields,methodparameters,andlocalvariables
∙UsetheExpressionsviewtowatchvariablesduringdebugging
∙AssignDetailFormattersthatcustomizeobjectdisplaywhenexistingtoString()methodsareinadequate
Reading
7.1.StartaDebugSession
Youcanusethedebuggingfeaturesinanyperspective;
however,theDebugPerspectiveisdesignedspecificallytosupporttheseactivities.It'
seasiesttostartanewdebugsessionfromtheJavaPerspectiveandthenswitchtotheDebugPerspective.Ofcourse,youcanmovefreelybetweenperspectivesatanytime.
Startadebugsessionbyright-clickingontheMain.javaentryfromthecom.eclipsedistilled.catalogpackageinthePackageExplorerviewandselectingDebugAs>
JavaApplicationfromthecontextmenu.Alternatively,selectDebug>
Debug…fromthecontextmenutoopenadialog,asshowninFigure7-1.PresstheNewbuttontocreateanewlaunchconfigurationforrunningtheMain.javaclass.PresstheDebugbuttontostartadebugsession.
Figure7-1.Createalaunchconfigurationforyourapplication.
OurMain.javaapplicationdoesnotrequireconfigurationbecausetheprojectbuildpathisusedbydefaultwhenrunningthisprogram.However,youcanlaunchanddebugmuchmorecomplexapplicationswithintheEclipseworkbench.AnythingthatcanberunasaJavaapplication(i.e.,anythingthathasamain()method)canberuninthedebugger,suchasaSwing-basedGUIapplicationoracompleteapplicationserversuchasTomcatorJBoss.Thelaunchconfigurationdialogincludestabsforspecifyingcommand-linearguments,classpathlocations,andenvironmentvariablesneededtostarttheapplication.OtherdebugconfigurationsareshownontheleftsideofthisdialogforrunningJavaApplets,JUnittests,oraruntimeinstanceoftheEclipseworkbenchitselfusedwhendebuggingplug-ins.
Afteryouhaverunanapplication,itappearsinthelistofrecentlyrunconfigurationsundertheRunandDebugtoolbarmenus.TheDebugmenuisshowninFigure7-2withoneentryforMain(youcanrenamethisentryintheconfigurationdialog,forexampletoCatalogApp).SelectMaintostartthedebugsession,orselectDebug…toopentheconfigurationdialogandmodifythelaunchparametersbeforestarting.YoucanalsopressF11todebugthepreviouslylaunchedconfiguration.
Figure7-2.Rerunorconfigureapreviousdebugsessionusingthetoolbarmenu.
Ifwerunthisapplicationbeforesettinganybreakpoints,itwilllookmuchlikethewayweranitinChapter2.TheConsoleviewdisplaysourmessagesandacceptsuserinputfromthecommandline.
NowswitchtotheDebugPerspectivebyselectingWindow>
OpenPerspective>
Debugfromtheworkbenchwindowmenu.Youcanusetheperspectivebartoswitchbetweenopenperspectives.
StartyourdebuggingworkbyusingtheConsoletoaddtwoproductstothecatalog.Now,presstheSuspendbuttonontheDebugviewtoolbarorpickRun>
Suspendfromtheworkbenchmenu.Thedebugviewswillappear,asshowninFigure7-3.Theapplicationexecutionthreadissuspended,andyoucanselectanystackframefromthecallstackintheDebugview.TheVariablesviewshowsfields,localvariables,andmethodparametersfortheselectedframe.ThisfigureshowsanexpandedviewofthecatalogfieldfromaMainclassinstance.
Figure7-3.Suspendexecutionwhilewaitingforconsoleinput.
Youcanaddorremovebreakpointsinthesourcecodeatanytime.AddabreakpointwithintheJavaeditorbydouble-clickingintheleftrulerbesidealinewhereyouwantabreakpoint.Ablueballappearstomarkthebreakpoint.
Figure7-4.Createanewbreakpointbydouble-clickingintheleftruler.
NowpresstheResumebuttonontheDebugviewtoolbar.AddanewcatalogitemintheconsoleviewandpresstheEnterkey.Theexecutionwillsuspendwhenithitsthebreakpoint,displayingtheviewsshowninFigure7-5.
Figure7-5.Inspectvariableswhilesteppingthroughyourprogram.
Whenaprogramthreadissuspended,theDebugviewshowsoneormorestackframesforthatthread.Astackframeshowstheexecutioncontextcontaininglocalvariablesandargumentsforthemethodinthatpositionofthecallstack.
Asyoustepthroughaprogram'
sexecution,thesourcecodelinesarehighlightedtotrackyourprogress.TwokindsofprogressstepsarehighlightedinFigure7-5.TheCurrentInstructionPointercontainsthestatementthatwillbeexecutednextwhenthethreadresumes.TheDebugCallStackmarksthelinewheretheselectedstackframewassuspended.Inthisexample,wehaveselectedapreviousstackframethatshowstheprogramstatebeforesteppingintothecurrentstatement,getItems().
7.1.1.SteppingThroughExecution
Afterexecutionhassuspendedonabreakpoint,thereareseveraloptionsforresumingorsteppingthroughtheprogramstatement-by-statement.Youcanterminateaprogramatanytimewhileit'
srunningorsuspended.Figure7-6showsthemenuitemsavailableintheworkbenchRunmenuwhenaprogramthreadissuspended.TheSuspendcommandisdisabledforthatthreadbecauseitisalreadysuspended.
Figure7-6.Commandsusedtostepthroughtheexecutionofaprogram.
Thefirstthreecommandsprovidethemostgeneralcontrol:
Resume.Resumeexecutionofathreaduntiliteitherendsorencountersabreakpoint.
Suspend.Suspendanexecutingthread.
Terminate.TerminatetheJavaVM.
BehaviorofthestepcommandsisrelativetothestackframefortheselectedthreadintheDebugview.Forallcommands,thecurrentlineofexecutionintheselectedstackframeishighlightedintheeditor.
StepInto.Stepintothenextexecutedmethod.Steppingintoamethodcausesthestackframetogrowbyone.
StepOver.Finishexecutionofthecurrentlineandsuspendonthenextexecutableline.
StepReturn.Stepoutofthecurrentmethod.Executionresumesuntilareturnstatementisexecutedinthecurrentmethod.
RuntoLine.Resumeexecutionuptotheselectedline.Thisisaconvenientwaytosuspendexecutionatalinewithoutsettingabreakpoint.
UseStepFilters.Whenthiscommandistoggledon,eachofthestepcommandswillapplythesetofstepfiltersthataredefinedintheuserpreferencespageJava>
Debug>
StepFiltering.Whenastepactionisinvoked,steppingwillcontinueuntilanunfilteredlocationisreachedorabreakpointisencountered.
Ifabreakpointisencounteredwhileperformingastepoperation,theexecutionwillsuspendatthebreakpoint,andthestepoperationisended.
TheRuntoLinecommandisnotontheDebugviewtoolbar.Placeyourcursoronthelineatwhichyouwanttheprogramtobesuspended.SelectRuntoLinefromtheworkbenchRunmenuortheJavaeditorcontextmenu,orpressCtrl+R.Bydefault,RuntoLinestopsifabreakpointisencounteredbeforereachingtheselectedline(aswithotherstepoperations).However,thereisasettingontheRun/DebugpreferencespagetoskipbreakpointsduringRuntoLineifyou'
dliketoavoidthisbehavior.
7.2.InspectingandDisplayingState
TheVariablesviewshowsfields,localvariables,andmethodparametersfortheselectedstackframe.Thestackframeprovidestheexecutioncontextforthesevariables.SelectoneofthesevariablestodisplayitsvalueintheDetailspaneofthisviewnotethattheDetailspaneatthebottomofthisviewisdistinctfromtheDisplayview,althoughtheyhaveasimilarpurpose.Ifthevariablecontainsanobject,asopposedtoaprimitive,youcanalsoexpandthatobjecttodisplayitsmembervariables.RefertoFigures7-3and7-5,whichdisplayvaluesoftheCatalogmembervariables.TheDisplayviewisnotopenbydefault;
openitwhileintheDebugperspectiveusingthemenuWindow>
ShowView>
Display.PleasebeawareofthedifferencebetweentheDetailspaneandDisplayviewinthefollowingdiscussion.
TheDetailspanecanalsobeusedtoevaluatecodesnippets.Thisevaluationoccurswithinthecontextoftheselectedvariable,orifnovariableisselected,thentheselectedstackframecontextisused.Youmustbeawareofthiscontextbecauseitdeterminesthevalueoftheidentifierthisandalsodetermineswhichothervariablenamesareavailablewithinthecodesnippet.InFigure7-7weenteredasnippet.forexample:
Catalogcatalog=newCatalog();
Stringitem="
hello"
;
catalog.getItems().add(item);
System.out.println("
Product:
"
+item);
Figure7-7.Executeacodesnippetduringdebugging.
Toexecutethiscodesnippet,dothefollowing:
1.SelectthedesiredCatalogIteminstancewithintheCatalogitemsvariable.
2.SelecttheentireexpressionintheDetailspane;
alternat