Tải bản đầy đủ - 0 (trang)
Chapter 16. Throwing and Catching Exceptions

Chapter 16. Throwing and Catching Exceptions

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

Ideally,aftertheexceptioniscaught,theprogramcanfixthe

problemandcontinue.Evenifyourprogramcan'tcontinue,by

catchingtheexception,youhaveanopportunitytoprinta

meaningfulerrormessageandterminategracefully.







16.1.Bugs,Errors,andExceptions

Itisimportanttodistinguishexceptionsfrombugsanderrors.

Abugisaprogrammermistakethatshouldbefixedbeforethe

codeisshipped.Anexceptionisnottheresultofaprogrammer

mistake(thoughsuchmistakescanalsoraiseexceptions).

Rather,exceptionsareraisedasaresultofpredictablebut

unpreventableproblemsthatarisewhileyourprogramis

running(e.g.,anetworkconnectionisdroppedoryourunout

ofdiskspace).

Anerroriscausedbyuseraction.Forexample,theusermight

enteranumberwherealetterisexpected.Onceagain,anerror

mightcauseanexception,butyoucanpreventthatby

implementingcodetovalidateuserinput.Wheneverpossible,

usererrorsshouldbeanticipatedandprevented.

Evenifyouremoveallbugsandanticipateallusererrors,you

willstillrunintopredictablebutunpreventableproblems,such

asrunningoutofmemoryorattemptingtoopenafilethatno

longerexists.Theseareexceptions.Youcannotprevent

exceptions,butyoucanhandlethemsothattheydonotbring

downyourprogram.



16.2.ThrowingExceptions

AllexceptionsareeitheroftypeSystem.Exceptionoroftypes

derivedfromSystem.Exception.Microsoftsuggeststhatallthe

exceptionsyouuseinyourprogramderivefromSystem.Exception,

thoughyouarealsofreetoderivefromSystem.ApplicationException

(whichwasthepreviousrecommendedstrategy).

TheCLRSystemnamespaceincludesanumberofpre-defined

exceptiontypesthatyoucanuseinyourownprograms.These

exceptiontypesincludeArgumentNullException,InvalidCastException,

andOverflowException,aswellasmanyothers.Youcanguess

theirusebasedontheirname.Forexample,ArgumentNull

exceptionisthrownwhenanargumenttoamethodisnullwhen

thatisnotanexpected(oracceptable)value.

Thischapterdescribeshowtowriteyourprogramstocatchand

handleexceptions.Thischapteralsoshowsyouhowtousethe

propertiesoftheExceptionclasstoprovideinformationtothe

useraboutwhatwentwrong,anditshowsyouhowtocreate

anduseyourowncustomexceptiontypes.



16.3.SearchingforanExceptionHandler

Whenyourprogramencountersanexceptionalcircumstance,

suchasrunningoutofmemory,itthrowsanexception.

Exceptionsmustbehandledbeforetheprogramcancontinue.

Ifthecurrentlyrunningfunctiondoesnothandletheexception,

thecurrentfunctionterminatesandthecallingfunctiongetsa

chancetohandletheexception(thisiscalled"unwindingthe

stack").Ifnoneofthecallingfunctionshandlesit,theexception

ultimatelyishandledbytheCommonLanguageRuntime(CLR),

whichabruptlyterminatesyourprogram.

Inotherwords,iffunctionAcallsfunctionB,andfunctionB

callsfunctionC,thesefunctioncallsareallplacedonthestack.

Whenaprogrammertalksabout"unwindingthestack,"whatis

meantisthatyoubackupfromCtoBtoA,asillustratedin

Figure16-1.



Figure16-1.Unwindingthestack



IfyoumustunwindthestackfromCtoBtoAtohandlethe

exception,whenyouaredone,youareinA;thereisno

automaticreturntoC.







16.4.ThethrowStatement

TosignalanabnormalconditioninaC#program,throwan

exceptionbyusingthetHRowkeyword.Thefollowinglineofcode

createsanewinstanceofSystem.Exceptionandthenthrowsit:

thrownewSystem.Exception();



Example16-1illustrateswhathappensifyouthrowan

exceptionandthereisnotry/catchblocktocatchandhandlethe

exception.Inthisexample,you'llthrowanexceptioneven

thoughnothinghasactuallygonewrong,justtoillustratehow

anexceptioncanbringyourprogramtoahalt.



Example16-1.Unhandledexception



usingSystem;

namespaceUnhandledException

{

classTester

{

staticvoidMain()

{

Console.WriteLine("EnterMain...");

Testert=newTester();

t.Run();

Console.WriteLine("ExitMain...");

}

publicvoidRun()

{

Console.WriteLine("EnterRun...");

Func1();

Console.WriteLine("ExitRun...");

}

publicvoidFunc1()

{



Console.WriteLine("EnterFunc1...");

Func2();

Console.WriteLine("ExitFunc1...");

}

publicvoidFunc2()

{

Console.WriteLine("EnterFunc2...");

thrownewApplicationException();

//thisnextlinecanneverexecute

Console.WriteLine("ExitFunc2...");

}

}

}



Theoutputlookslikethis:

EnterMain...

EnterRun...

EnterFunc1...

EnterFunc2...



UnhandledException:System.Exception:Exceptionoftype

System.Exceptionwasthrown.at

ExceptionHandling.Tester.Func2()insource\exceptions\exc

34

atExceptionHandling.Tester.Func1()insource\exceptions

line27

atExceptionHandling.Tester.Run()insource\exceptions\e

line19

atExceptionHandling.Tester.Main()insource\exceptions\

line13



Whenyourunthiscode,you'llalsoreceiveawarningthatthefollowing

lineisunreachable:

Console.WriteLine("ExitFunc2...");



That'sbecausethecompilercantellthatthere'snowaythislinewill

everbereached.Inthisexample,youcanignorethewarning,butas

notedearlier,youshouldusuallytrytowritewarning-freecode.



Thissimpleexamplewritestotheconsoleasitentersandexits

eachmethod.Main()callsRun(),whichinturncallsFunc1().

Afterprintingoutthe"EnterFunc1"message,Func1()

immediatelycallsFunc2().Func2()printsoutthefirstmessage

andthrowsanobjectoftypeSystem.Exception.

Executionimmediatelystops,andtheCLRlookstoseeifthere

isahandlerinFunc2().Thereisnot,andsotheruntime

unwindsthestack(neverprintingtheexitstatement)toFunc1(

).Again,thereisnohandler,andtheruntimeunwindsthestack

backtoMain().Withnoexceptionhandlerthere,thedefault

handleriscalled,whichprintstheerrormessage,and

terminatestheprogram.







16.5.ThetryandcatchStatements

Asyousaw,theexceptioninyourpreviousexamplestopped

yourprogramdead.That'susuallynotthedesiredbehavior.

Whatyouneedisawaytotellthecompiler,"Ifanyexceptions

arethrowninthissectionofcode,takethisaction."Thatway,

yourprogramcancontinueonfromtheerror,oratleastend

gracefully.Thisprocessiscalledhandlingtheexception.To

handleexceptions,takethefollowingsteps:

1. Executeanycodethatyoususpectmightthrowan

exception(suchascodethatopensafileorallocates

memory)withinaTRyblock.

2. Catchanyexceptionsthatarethrowninacatchblock.

Atryblockiscreatedusingthekeywordtryandisenclosedin

braces.Thetryblockistheareaofcodewhereyouwantto

watchforexceptions.Acatchblockholdsthecodewhereyou

takeactionbasedonthetypeofexceptionthrown.Itiscreated

usingthekeywordcatchandisalsoenclosedinbraces.Example

16-2illustratestheseconstructs.NotethatExample16-2is

identicaltoExample16-1exceptthatnowtheprogramincludes

aTRy/catchblock.



Example16-2.Tryandcatchblocks



usingSystem;

namespaceTryAndCatchBlocks

{

classTester

{

staticvoidMain()

{

Console.WriteLine("EnterMain...");

Testert=newTester();



t.Run();

Console.WriteLine("ExitMain...");

}

publicvoidRun()

{

Console.WriteLine("EnterRun...");

Func1();

Console.WriteLine("ExitRun...");

}



publicvoidFunc1()

{

Console.WriteLine("EnterFunc1...");

Func2();

Console.WriteLine("ExitFunc1...");

}

publicvoidFunc2()

{

Console.WriteLine("EnterFunc2...");

try

{

Console.WriteLine("Enteringtryblock...");

thrownewApplicationException();

//thiscodeneverexecutesbecauseoftheexception

Console.WriteLine("Exitingtryblock...");

}

catch

{

Console.WriteLine("Exceptioncaughtandhandled!");

}

Console.WriteLine("ExitFunc2...");

}

}

}



Theoutputlookslikethis:

EnterMain...

EnterRun...

EnterFunc1...

EnterFunc2...

Enteringtryblock...

Exceptioncaughtandhandled!

ExitFunc2...

ExitFunc1...



ExitRun...

ExitMain...



Followingthetrystatementisthecatchstatement.Inareal

catchstatement,youmightsilentlyfixtheproblem(for

example,byretryingadatabaseconnection),oryoumight

interactwiththeusertosolvetheproblem(suchasofferingthe

usertheopportunitytocloseotherapplicationsandfreeup

memory).InExample16-2,thecatchstatementsimplyreports

thattheexceptionhasbeencaughtandhandled.

Noticethattheexitstatementsarenowwritten.Withthe

exceptionhandled,executionresumesimmediatelyafterthe

catchblock.







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

Chapter 16. Throwing and Catching Exceptions

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

×