Tải bản đầy đủ - 0 (trang)
Chapter 6. Exceptions and Error Handling

Chapter 6. Exceptions and Error Handling

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

6.0Introduction

Thisrecipecoversthevarioustopicsassociatedwithexceptions

anderrorhandling.Asyouwillundoubtedlyfindout,exceptions

areprevalentthroughoutthe.NETFramework,andthe.NET

documentationdoesagoodjoboftellingwhichexceptionsare

thrownwhere.Weencourageyoutobecomeasintimately

familiarwithexceptionsanderror-handlingdiagnosticsas

possibleandtoputthetechniquesinthischaptertouseasyou

code,notlater.Ifyoudodecidetoputitoffuntillater,realize

thatmoreoftenthannotyouwillmisssomekeycoverage

pointsforerrorhandlingwithinyourapplication.



6.1Usingtry/catchblocks

Yourealizethatacertainblockofcodemightthrowanexception,so

youwanttocreateahandlertocatchtheexceptionifitisthrown.



Technique

Wrapthecodethatmightthrowanexceptionwithinatry

block.Atryblockconsistsofthetrykeywordandabody

withincurlybraces.Ifanexceptionisthrownwithinthatbody,

thecatchhandlerwillexecute.Thecatchblockcontainsthe

keywordcatchfollowedbytheexceptiontypeyouwantto

catchandanoptionalvariableidentifierforthatexception.The

bodyofthecatchblockcontainsthecodenecessarytorespond

tothatexception,asshowninListing6.1.



Listing6.1Usingatry/catchBlocktoHandle

Exceptions



usingSystem;



namespace_1_TryCatch

{

classClass1



{

[STAThread]

staticvoidMain(string[]args)

{

try

{

//askforandreadanumberfromtheuser

Console.Write("Enteranumber:");

intinput=Int32.Parse(Console.ReadLine());



//thelastiterationinthisloopwillattempt

//dividebyzero

for(inti=5;i>=0;i)



Console.WriteLine("{0}/{1}={2}",input,i,

}

catch(Exceptione)

{

//displayexceptionmessage



Console.WriteLine("Anerroroccurred:{0}",e.

}

}

}

}



Comments

InListing6.1,youcanseeanobviouserror.Asthecounterfor

theloopreaches0,theprogramattemptstodivideusingthat

value.Naturally,youjustwanttochangethecoderatherthan

useexceptionhandlinginthiscase,butsometimessucherrors

aren'teasytodiscover.

Whenyouwrapablockofcodewithinatryblock,youcover

everymethodthatiscapableofthrowinganexception.Ifanyof

themethodcallsoroperationswithinthiscodeblockthrowan

exception,theyallsharethesamecatchblock.Youcan,

however,fine-tunethecatchblocktocatchdifferentexceptions

andreactaccordingly.Todoso,simplycreatemultiplecatch

blocks.Tocatchthedivide-by-zeroexceptioninListing6.1,for

example,createasecondcatchblockwhoseparameteris

DivideByZeroException.NotethatbyusingExceptionasthe

exceptionclasstocatch,youwillcatchanyexceptionthat

occursregardlessofthetypethatisthrown.

Furthermore,ifanexceptioniscaughtwithinacatchblock,the

remainingcatchblocksdonotexecute.Whentheexceptionis

thrownwithinthecodelistingthatfollows,itiscaughtinthe

firstcatchblockandnotthecatchblockthatfollows:



try

{

//dividebyzerocodehere

}

catch(DivideByZeroException)

{

}

catch(Exception)

{

}

Iftheexceptionisnothandled,theCommonLanguageRuntime

(CLR)exceptiondialogappears,asshowninFigure6.1.When

youclosethedialog,theruntimeaccessestheMessageand

StackTracepropertiesoftheexceptionobjectanddisplaysthat

informationwithintheconsole,assumingitisaconsole

application.Furthermore,becausetheexceptionwasnot

handledusingthetechniquesdescribedinthisrecipe,the

runtimewillprematurelyaborttheapplication.If,ontheother

hand,youdohandletheexceptionusingacatchblock,your

programcontinuesatthenextinstructionfollowingthelast

catchblock.Thisbehaviorallowsyourapplicationtocontinue



eventhoughanerrorwasdetected.Forinstance,inthe

exampleshownearlier,iftheresultsofthecomputationare

placedintoanarray,youcansimplyskipthecomputationthat

causedthedivide-by-zeroerrorandcontinueprocessingthose

results,perhapslogginganerroralongtheway.



Figure6.1.Unhandledexceptionsresultinthe

displayoftheCLRexceptiondialog.



6.2UsingafinallyBlock

Youwanttoexecuteabodyofcodewhetherornotanexceptionis

thrown.



Technique

Youcanuseafinallyblocktoexecuteablockofcodeafter

executingthecorrespondingtry/catchblocks.Immediately

followingacatchblockormultiplecatchblocks,usethe

keywordfinallyfollowedbyacodeblockwithincurlybraces.

Listing6.2showsatryblockfollowedbytwocatchblocks.The

finallyblockinthecoderunswhetheranexceptionisthrown

ornot.



Listing6.2AddingafinallyBlock



usingSystem;



namespace_1_TryCatch

{

classClass1

{



[STAThread]

staticvoidMain(string[]args)

{

try

{

//retrievenumberfromuser

Console.Write("Enteranumber:");

intinput=Int32.Parse(Console.ReadLine());



//lastiterationattemptstodividebyzero

for(inti=5;i>0;i--)



Console.WriteLine("{0}/{1}={2}",input,i,

}

catch(DivideByZeroException)

{



Console.WriteLine("Programattemptedtodivide

}

catch(Exceptione)



{



Console.WriteLine("Anerroroccurred:{0}",e.

}

finally

{

Console.WriteLine("Programhasfinished.");

}

}

}

}



Comments

Whenanexceptionisthrown,theremainderofatryblock

doesnotexecute,andcontrolistransferredtoacatchblock.

Anyextraprocessingyouhavealongthelinesofcleaningup

resources,ensuringoutparametersaresetcorrectly,or

manipulatinganyinternalvariablesisskipped.Ifyouwereto

putthatinformationwithinacatchblockinsteadofatry

block,thenofcourseitwouldn'texecuteifanexceptionwere

neverthrown.Youcouldplaceduplicatecodewithinthetryand

catchblocks,butthissolutionobviouslyisn'tclean.The

finallyblockexecutescommoncodethatneedstobe

executedfollowingeithertheendofatryblockortheendofa

catchblock.



Itisafairquestiontoaskwhyyouevenneedafinallyblock

inthefirstplace.Afterall,thelinesofcodefollowingthetry

andcatchblocksisexecutedanyway.Thatistrue,andyouare

freetousethattoyouradvantage.However,usingafinally

blockkeepsanyvariablesdeclaredwithinthetryblockin

scope.Oncetheexception-handlingblocksareexited,any

variablesthatweredeclaredwithinthetryblockarenolonger

validandcannotbeused.Therefore,youwanttofreeany

resourcesthatwerecreatedwithinthetryblock,whichcan

includeanyopenstreamsordatabaseconnections,for

example.



6.3DisplayingExceptionInformation

Youwanttodisplayinformationaboutanexceptiontoaidintracking

downwhyitoccurs.



Technique

Everyexceptionthatyoucancatchisderivedfromthe

System.Exceptionclass.Withinthatclassareseveral

propertiesthatyoucanaccesstoacquiremoreinformation.The

mostfrequentlyusedpropertyisMessage,whichreturnsa

readablestringdetailingtheerror.Additionalpropertiesinclude

Source,whichdisplaysthenameoftheapplicationwherethe

exceptionoccurred,andTargetSite,whichdisplaysthename

ofthemethodthatwascurrentlyexecutingwhentheexception

wasthrown.

Toviewthemethodscurrentlyinscope,youcanviewthecall

stackbyaccessingtheStackTracestring.Finally,ifyouwantto

determinewhetheranexceptionwasthrownbyanapplication,

catchtheApplicationExceptionexceptionobject,andifyou

wanttodeterminewhethertheexceptionbeingthrownisfrom

theCLR,catchtheSystemExceptionobject.Listing6.3

demonstrateshowtodisplayexceptioninformationbythrowing

avarietyofexceptionsbasedonauser'sinput.



Listing6.3DisplayingExceptionInformation



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

Chapter 6. Exceptions and Error Handling

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

×