设为首页 - 加入收藏 站长在线 - 常用服务器软件 - 在线站长工具 - 在线伪原创工具
您的当前位置:主页 > 网络教程 > ASP.NET > 正文

asp.net 的错误处理机制讲解

来源:ZzWww 编辑:ZzWww 时间:2019-04-02

程序健壮性最基本要求就是程序错误的处理与捕捉,在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


TAG标签:asp.net 错误 处理 讲解 机制

网友评论:

文章右边250
Top