Chapter 7 Debugging Your Code.docx

上传人:b****7 文档编号:10182697 上传时间:2023-02-09 格式:DOCX 页数:12 大小:639.68KB
下载 相关 举报
Chapter 7 Debugging Your Code.docx_第1页
第1页 / 共12页
Chapter 7 Debugging Your Code.docx_第2页
第2页 / 共12页
Chapter 7 Debugging Your Code.docx_第3页
第3页 / 共12页
Chapter 7 Debugging Your Code.docx_第4页
第4页 / 共12页
Chapter 7 Debugging Your Code.docx_第5页
第5页 / 共12页
点击查看更多>>
下载资源
资源描述

Chapter 7 Debugging Your Code.docx

《Chapter 7 Debugging Your Code.docx》由会员分享,可在线阅读,更多相关《Chapter 7 Debugging Your Code.docx(12页珍藏版)》请在冰豆网上搜索。

Chapter 7 Debugging Your Code.docx

Chapter7DebuggingYourCode

Chapter7.DebuggingYourCode

Understandingtheoperationofcomplexsoftwareoftenrequiresintrospectionthatgoesbeyondthedisplayofloginformationusingprintln()statementsandlog4joutput.Youneedtheabilitytostepthroughaprogramstatement-by-statementandviewormodifythestateoffields,methodparameters,andlocalvariables.

OurdebuggingactivitiesarefocusedontheproductcatalogprojectthatwasintroducedinChapter2,"HelloEclipse."WeinitiallyrantheapplicationwithinEclipseusingtheConsoleviewforcommand-lineinputandoutput.Nowwewillrunthesameprojectwithinthedebugger,whichenablesdetailedanalysisofitscontrolflowandstate.IfyouarenewtoJava,andespeciallyifyouarenewtoobject-orientedprogramming,steppingthroughyourcodeinthedebuggerisanexcellentwaytounderstandhowitruns.

Coursepoints

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

展开阅读全文
相关资源
猜你喜欢
相关搜索

当前位置:首页 > 表格模板 > 合同协议

copyright@ 2008-2022 冰豆网网站版权所有

经营许可证编号:鄂ICP备2022015515号-1