Tải bản đầy đủ - 0 (trang)
Appendix C. Using the Visual Studio 2005 Debugger

Appendix C. Using the Visual Studio 2005 Debugger

Tải bản đầy đủ - 0trang

AppendixC.UsingtheVisualStudio

2005Debugger

Wearebuilttomakemistakes,codedforerror.

LewisThomas

Whatweanticipateseldomoccurs;whatweleast

expectgenerallyhappens.

BenjaminDisraeli

Itisonethingtoshowamanthatheisinerror,and

anothertoputhiminpossessionoftruth.

JohnLocke

Hecanrunbuthecan'thide.

JoeLouis

AndsoshallIcatchthefly.

WilliamShakespeare

OBJECTIVES

Inthisappendixyouwilllearn:

Tousethedebuggertolocateandcorrectlogicerrorsina

program.

Tousebreakpointstopauseprogramexecutionandallow

youtoexaminethevaluesofvariables.



Toset,disableandremovebreakpoints.

TousetheContinuecommandtocontinueexecutionfroma

breakpoint.

TousetheLocalswindowtoviewandmodifyvariable

values.

TousetheWatchwindowtoevaluateexpressions.

TousetheStepInto,StepOutandStepOvercommandsto

executeaprogramline-by-line.

TousethenewVisualStudio2005debuggingfeaturesEdit

andContinueandJustMyCode™debugging.



[Page1441]



Outline

C.1 Introduction

C.2 BreakpointsandtheContinueCommand



C.3 TheLocalsandWatchWindows



C.4 ControllingExecutionUsingtheStepInto,StepOver,StepOut

andContinueCommands



C.5 OtherFeatures













C.5.1 EditandContinue

C.5.2 ExceptionAssistant

C.5.3 JustMyCode™Debugging

C.5.4 OtherNewDebuggerFeatures



C.6 Wrap-Up

Summary

Terminology

Self-ReviewExercises

AnswerstoSelf-ReviewExercises







[Page1441(continued)]



C.1.Introduction

InChapter3,youlearnedthattherearetwotypesof

errorscompilationerrorsandlogicerrorsandyoulearnedhowto

eliminatecompilationerrorsfromyourcode.Logicerrors,also

calledbugs,donotpreventaprogramfromcompiling

successfully,butcancauseaprogramtoproduceerroneous

results,orterminateprematurely,whenitruns.Mostcompiler

vendors,likeMicrosoft,provideatoolcalledadebugger,which

allowsyoutomonitortheexecutionofyourprogramstolocate

andremovelogicerrors.Aprogrammustsuccessfullycompile

beforeitcanbeusedinthedebuggerthedebuggerhelpsyou

analyzeaprogramwhileitisrunning.Thedebuggerallowsyou

tosuspendprogramexecution,examineandsetvariablevalues

andmuchmore.Inthisappendix,weintroducetheVisual

Studiodebugger,severalofitsdebuggingtoolsandnew

featuresaddedforVisualStudio2005.



[Page1441(continued)]



C.2.BreakpointsandtheContinueCommand

Webeginbyinvestigatingbreakpoints,whicharemarkersthat

canbesetatanyexecutablelineofcode.Whenarunning

programreachesabreakpoint,executionpauses,allowingyou

toexaminethevaluesofvariablestohelpdeterminewhether

logicerrorsexist.Forexample,youcanexaminethevalueofa

variablethatstorestheresultofacalculationtodetermine

whetherthecalculationwasperformedcorrectly.Youcanalso

examinethevalueofanexpression.

Toillustratethefeaturesofthedebugger,weusetheprogram

inFigs.C.1andC.2,whichcreatesandmanipulatesanobject

ofclassAccount(Fig.C.1).Thisexampleissimilartoanexample

yousawinChapter4(Figs.4.154.16).Therefore,itdoesnot

usefeatureswepresentinlaterchapterslike+=andif...else.

ExecutionbeginsinMain(lines829ofFig.C.2).Line10creates

anAccountobjectwithaninitialbalanceof$50.00.Account's

constructor(lines1013ofFig.C.1)acceptsoneargument,

whichspecifiestheAccount'sinitialbalance.Lines1314ofFig.C.2

outputtheinitialaccountbalanceusingAccountpropertyBalance.

Line16declaresandinitializeslocalvariabledepositAmount.Lines

1920prompttheuserforandinputthedepositAmount.Line23

addsthedeposittotheAccount'sbalanceusingitsCreditmethod.

Finally,lines2627displaythenewbalance.



[Page1442]

FigureC.1.Accountclasswithaconstructorto

initializeinstancevariablebalance.



1//Fig.C.01:Account.cs



2//Accountclasswithaconstructorto

3//initializeinstancevariablebalance.

4

5publicclassAccount

6{

7privatedecimalbalance;//instancevariablethatstoresthebalance

8

9//constructor

10publicAccount(decimalinitialBalance)

11{

12Balance=initialBalance;//setbalanceusingpropertyBalance

13}//endAccountconstructor

14

15//credit(add)anamounttotheaccount

16publicvoidCredit(decimalamount)

17{

18Balance=Balance+amount;//addamounttoBalance

19}//endmethodCredit

20

21//apropertytogetandsettheaccountbalance

22publicdecimalBalance

23{

24get

25{

26returnbalance;

27}//endget

28set

29{

30//validatethatvalueisgreaterthan0;

31//ifitisnot,balanceissettothedefaultvalue0

32if(value>0)

33balance=value;

34

35if(value<=0)

36balance=0;

37}//endset

38}//endpropertyBalance

39}//endclassAccount



FigureC.2.CreatingandmanipulatinganAccount

object.



1//Fig.C.02:AccountTest.cs

2//CreateandmanipulateanAccountobject.

3usingSystem;

4

5publicclassAccountTest

6{



7//MainmethodbeginsexecutionofC#application

8publicstaticvoidMain(string[]args)

9{

10Accountaccount1=newAccount(50.00M);//createAccountobject



[Page1443]

11

12//displayinitialbalanceofeachobjectusingpropertyBalance

13Console.Write("account1balance:{0:C}\n",

14account1.Balance);//displayBalanceproperty

15

16decimaldepositAmount;//depositamountreadfromuser

17

18//promptandobtainuserinput

19Console.Write("Enterdepositamountforaccount1:");

20depositAmount=Convert.ToDecimal(Console.ReadLine());

21Console.Write("adding{0:C}toaccount1balance\n\n",

22depositAmount);

23account1.Credit(depositAmount);//addtoaccount1balance

24

25//displaybalance

26Console.Write("account1balance:{0:C}\n",

27account1.Balance);

28Console.WriteLine();

29}//endMain

30}//endclassAccountTest



account1balance:$50.00

Enterdepositamountforaccount1:49.99

adding$49.99toaccount1balance

account1balance:$99.99



Inthefollowingsteps,youwillusebreakpointsandvarious

debuggercommandstoexaminethevalueofthevariable

depositAmount(declaredinFig.C.2)whiletheprogramexecutes.

1. InsertingbreakpointsinVisualStudio.First,ensurethat

AccountTest.csisopenintheIDE'scodeeditor.Toinserta

breakpoint,leftclickinsidethemarginindicatorbar(the

graymarginattheleftofthecodewindowinFig.C.3)next



tothelineofcodeatwhichyouwishtobreak,orrightclick

thatlineofcodeandselectBreakpoint>InsertBreakpoint.You

cansetasmanybreakpointsasyoulike.Setbreakpointsat

lines19,23and28ofyourcode.Asolidcircleappearsin

themarginindicatorbarwhereyouclickedandtheentire

codestatementishighlighted,indicatingthatbreakpoints

havebeenset(Fig.C.3).Whentheprogramruns,the

debuggersuspendsexecutionatanylinethatcontainsa

breakpoint.Theprogramthenentersbreakmode.

Breakpointscanbesetbeforerunningaprogram,inbreak

modeandduringexecution.



FigureC.3.Settingbreakpoints.

(Thisitemisdisplayedonpage1444intheprintversion)

[Viewfullsizeimage]



2. Beginningthedebuggingprocess.Aftersetting

breakpointsinthecodeeditor,selectBuild>BuildSolutionto

compiletheprogram,thenselectDebug>StartDebugging(or



presstheF5key)tobeginthedebuggingprocess.While

debuggingaconsoleapplication,theCommandPrompt

windowappears(Fig.C.4),allowingprograminteraction

(inputandoutput).



[Page1444]



FigureC.4.Accountprogramrunning.

[Viewfullsizeimage]



3. Examiningprogramexecution.Programexecution

pausesatthefirstbreakpoint(line19),andtheIDE

becomestheactivewindow(Fig.C.5).Theyellowarrowto

theleftofline19indicatesthatthislinecontainsthenext

statementtoexecute.TheIDEalsohighlightsthelineas

well.



FigureC.5.Programexecutionsuspendedatthe

firstbreakpoint.

[Viewfullsizeimage]



[Page1445]

4. UsingtheContinuecommandtoresumeexecution.To

resumeexecution,selectDebug>Continue(orpresstheF5

key).TheContinuecommandwillexecutethestatements

fromthecurrentpointintheprogramtothenextbreakpoint

ortheendofMain,whichevercomesfirst.Theprogram

continuesexecutingandpausesforinputatline20.Enter

49.99intheCommandPromptwindowasthedeposit

amount.WhenyoupressEnter,theprogramexecutesuntil

itstopsatthenextbreakpoint(line23).Noticethatwhen

youplacethemousepointeroverthevariablename

depositAmount,itsvalueisdisplayedinaQuickInfobox(Fig.

C.6).Asyou'llsee,thiscanhelpyouspotlogicerrorsin

yourprograms.



FigureC.6.QuickInfoboxdisplaysvalueof

variabledepositAmount.

[Viewfullsizeimage]



Tài liệu bạn tìm kiếm đã sẵn sàng tải về

Appendix C. Using the Visual Studio 2005 Debugger

Tải bản đầy đủ ngay(0 tr)

×