程序健壮性最基本要求就是程序错误的处理与捕捉,在ASP.NET中,错误的处理有和其他编程语言一样的机制,可以使用Try…Catch…Finally等方式,这一点和ASP相比具有较大的进步。而且,使用这些错误处理方法,可以大大提高程序的可读性和程序调试速度,在这几个优势结合的情况下,我们更加应该注意这一点。
关于错误的处理,我们可以参考这篇文章:
Try...Catch...FinallyinASP.NET
Introduction
ErrorhandlinginClassicASPwasnotthebest.WewerehavingonlylimitedoptionsavailableforerrorhandlinginClassicASPsuchas,"OnErrorResumeNext".InASP3.0wesawthenewASPobjectcalledErrorObject.Butwewerenotabletohandleallexception/errorsefficiently.NowinASP.NETwehaveanewerrorhandlingmechanismwhichwasalreadytheirinotherlanguagessuchasC,C++andJAVA.Wecanalsocallthetry...catchmechanismas"ExceptionHandling"
WhatisTry...Catch....Finally
ThisisanewerrorhandlingmechanisminVB.NET,soasinASP.NET.Wellwehavethreeblocksofcode,wereeachblockhasitownfunctionality.TheTry...Catch...Finallyblockofcodesurroundsthecodewhereanexceptionmightoccur.ThesimpleTrystatementcomesbeforetheblockofcode,theCatchblockofcodeiswherewespecifywhattypeoferrortolookfor,andtheFinallyblockofcodeisalwaysexecutedandcontainscleanuproutinesforexceptionsituations.Sincethecatchblockisspecifictothetypeoferrorwewanttocatch,wewilloftenusemultipleCatchblocksinourTry...Catch...Finallystructure.
AsimpleDatabaseoperation
DimmySqlConnectionasNewSqlConnection(ConnectionString)
DimmySqlCommandasSqlCommand
DimstrSqlasString
strSql="insertintoyourtable(f1,f2)values('f1','f2')"
mySqlCommand=newSqlCommand(strSql,mySqlConnection)
Try
mySqlConnection.Open()
mySqlCommand.ExecuteReader(CommandBehavior.CloseConnection)
Message.text="NewForwardinformationadded"
CatchSQLexcassqlexception
Message.text=Message.text+sqlexc.tostring()
Catchexcasexception
ifInstr(1,exc.tostring,"duplicatekey")>0then
Message.text=Message.text+"Cannotinsertduplicatevalues."
else
Message.text=Message.text+exc.tostring()
endif
Finally
mySqlConnection.Close()
EndTry
Whatdoestheaboveexampleexactlydo?
Well,intheaboveexampleweweretryingtoinsertsomevaluestoadatabasetable.Thepossiblechanceswhileperformingadatabaseoperationareinvalidconnectionstring,databaseservertoobusyresultinginconnectiontimeout,databaseservernotcurrentlyrunningetcetc.Weshouldanticipatealltheseerrorswhileperformingadatabaseoperation.So,wehaveaTryblock,whichcontainsthestatementssuchasopeningtheconnectionandexecutingtheoperation.Basically,wehavetwomajorstatementsinsidethetryblockwhichmayresultinanexception/error.
AsIsaid,anyexceptioncanoccurduringadatabaseoperation.CatchingalltheseexceptionisnowveryeasywiththeCatchblock.AllweneedistohaveaCatchblock.WecanhaveanynumberofCatchblocks.EachCatchblockmayhaveadifferenterror/exceptiontrappingmechanism.Intheaboveexample,wehavetwocatchblocks,onewhichcapturesageneralexceptionandtheotheronewhichtrapstheSqlException.
Whenallthestatementsinsidethecatchblocksareexecuted,thefinallyblockcomesintothepicture.AsIsaidearlier,finallyblockcontainscleanuproutinesforexceptionsituations.
ExitTrystatement
WecanalsohavetheExitTrystatementinsideanyofthetry...catchblock.TheobjectiveofthisstatementistobreakoutoftheTryorCatchblock.OncetheExitTrystatementisexecuted,thecontrolgoestotheFinallyblock.So,ExitTrystatementcanbebestusedwereweneedtoexecutethecleanuproutines.
HowaboutnestedTrystatments?
WecanhavenestedTryandCatchblocks.Canyouimagine,whenweshouldusenestedtrystatements.Well,errorscanoccurwithintheCatchportionoftheTrystructures,andcausefurtherexceptiontooccur.TheabilitytonesttrystructuresisavailablesothatwecanuseasecondTrystructuretocoverexceptions.
Links
http://www.vbweb.co.uk/show/1889/2/http://www.oreillynet.com/pub/a/dotnet/2001/09/04/error_handling.html?page=2