Tải bản đầy đủ - 0 (trang)
Chapter 11.  Error Handling in Visual Basic

Chapter 11.  Error Handling in Visual Basic

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

11.1.ErrorDetectionandErrorHandling

Dealingwitherrorsinyourcodegenerallyoccursintwosteps:

errordetectinganderrorhandling.Inmostcases,youdealwith

theconsequencesofanerrorimmediately,mergingthesetwo

stepsintooneseamlessprocess.Youcanalsobreakupthe

steps,recognizinganerrorimmediatelybutdealingwithitlater

oninyourblockofcode,oreveninadifferentpartofyour

application.Thecodelocationwhereanerroroccursiscalled

theoffendingprocedure.

Therearetwotypesoferrorsthatcanoccurinarunning

program:runtimeerrorsandlogicerrors.Aruntimeerror

occurswhenthecodeattemptstoperformanoperationthatis

impossibletoperform,suchasopeningafilethatdoesnotexist

ordividingbyzero.VisualBasicautomaticallytakescareof

errordetectionofruntimeerrorsbecauseithasnootherchoice.

Propererrorhandlingofruntimeerrorsisuptothe

programmer.Withoutprogrammeraction,VisualBasicitself

handlestheerrorbypresentinganerrormessagetotheuser

andthenterminatingtheapplication,whichis,attheveryleast,

anuisancefortheuser.

Alogicerroristheproductionofanunexpectedorincorrect

result.ConsiderafunctionthatreturnstheIQforanindividual

basedonasetofIQtestscores.Aresultof100isentirely

normalandexpected.Ifanindividualisverysmart,youmight

expectanIQintherangeof120ormore.Butifthefunction

returnsanIQof-350,thatisalogicerror,eitherduetobad

code,baddata,orboth.

VisualBasicdoesnotprovideerrordetectionforlogicerrorsno

computerlanguagedoesbecausetoVisualBasic,noerrorhas

occurred.However,anunhandledlogicerrormaysubsequently

resultinaruntimeerror,whichVisualBasicwillcertainly

recognize.Forinstance,codethatisintendedtoretrievea



positivenonzerointegermayinsteadretrievezero.Thisisa

logicerror.Ifthatintegerislaterusedasadenominatorin

someotherpartoftheapplication,theseeminglysmalllogic

errorwillbecomealargeruntimeproblem.

Theprogrammermustanticipatelogicerrorsandprovideboth

errordetectionanderrorhandling.Fromthisperspective,logic

errorsarefarmoreseriousandmuchmoredifficulttodealwith

thanruntimeerrors.Afterall,aruntimeerrorwon'tbe

completelyoverlookedatleastVisualBasicwilldosomething

aboutit.

Theproblemwithanoverlookedlogicerroristhatitmaygive

theuserspeciousfeedback.Thisis,nodoubt,themost

insidiousbehavioraprogramcanproduce.Inthebest-case

scenario,alogicerrorwillgeneratearuntimeerroratsome

latertime,buttrackingdowntheoriginallogicerrorsourceof

thatruntimeerrormaybeadauntingtask.







11.2.RuntimeErrorHandling

VisualBasicsupportsbothunstructurederrorhandlingand

structuredexceptionhandling.Thisdiscussionstartswithalook

atunstructurederrorhandling,thesameerror-handling

supportprovidedinVB6.Youarenotrequiredtoincludeany

errorhandlinginaVBprocedure.Ifyoudoincludesuch

handlinginaprocedure,youmustincludeeitherthestructured

orunstructuredvariety;asingleprocedurecannotincludeboth

typesoferror-handlingmethods.



11.2.1.UnstructuredErrorHandling

Error-handlingtechniquesthatrevolvearoundthevariousOn

Error...statementsarereferredtoasunstructurederrorhandlingtechniques.ThesetechniquesgenerallyinvolvetheErr

objectandtheVisualBasiccallstack.



11.2.1.1.TheErrobject

VisualBasic'sbuilt-inerrorobject,calledErr,hasseveraluseful

propertiesandmethods,asshowninTables11-1and11-2,

respectively.

Table11-1.PropertiesoftheErrobject

Property



Description



Description



Ashortstringdescribingtheerror.



HelpContext



ThenumericcontextIDforahelptopicassociatedwiththeerror.



HelpFile



Thefullyqualifiedfilenameoftheassociatedhelpfile,ifavailable.



LastDLLError



ThereturncodefromacallmadetoafunctioninanexternalDLL.This

propertymaychangevalueatanytime,soitiswisetostorethecurrentvalue

inavariableimmediatelyuponreturnfromtheDLLcall.VBdoesnotraise

errorsbasedonthereturnvalueofaDLLfunction,sinceitcannotknowwhich

returnvaluesindicateerrors.



Number



Theerrornumberoftheerror.



Source



Astringthatindicatestheobjectthatgeneratedtheerror.Whentheerroris

generatedwithinyourapplication,theSourcepropertyistheproject

programmaticID.Forclass-initiatederrors,itisintheformatproject.class.

WhentheerrorisgeneratedbyanexternalCOMcomponent,theSource

propertyreturnstheprogrammaticIDofthatcomponent,generallyintheform

application.object.



Table11-2.MethodsoftheErrobject

Method Description

Clear



ClearsthevaluesofallpropertiesoftheErrobject.Itssyntaxis:

Err.Clear()



TheClearmethodiscalledimplicitlywhenanyofthefollowingstatementsare

executed:aResumestatement;anExitSub,ExitFunction,orExitPropertystatement;

atry...Catch...Finallystatement;oranOnErrorstatement.

Raise



CausesVisualBasictogeneratearuntimeerrorandsetsthepropertiesoftheErr

objecttothevaluesgivenbytheparametersoftheRaisemethod.Itssyntaxis:

Err.Raise(Number[,Source[,Description[,_

HelpFile[,HelpContext]]]])



whereallbutthefirstnamedargumentisoptional.Eachparametercorrespondsto

thepropertyofthesamename.



11.2.1.2.Dealingwithruntimeerrors

VisualBasicdetectsaruntimeerrorassoonasitoccurs,sets

thepropertiesoftheErrobject,anddirectstheflowof

executiontoalocationthattheprogrammerhasspecifiedby

themostrecentOnErrorstatement.Thislocationcanbeoneof

thefollowing:

Thelineofcodeimmediatelyfollowingthelinethatcaused

theerror

Anotherlabeledlocationwithintheoffendingprocedure

Anyenablederrorhandlerwithinthecurrentprocedure's

callstack

Newin2005.InWindowsFormsapplications,theerror

handlerassociatedwiththe

My.Application.UnhandledExceptionevent

Ifnoneofthesemethodsexistorareenabled(andno

structuredexceptionhandlersareinuse),VBissuesanerror

messageandterminatestheapplication.Theremainderofthis

sectiondescribeseachoptioninmoredetail.

Inlineerrorhandling.Codeexecutionwillbe"redirected"to

thelinefollowingtheoffendinglineofcodeifthemostrecentOn

Errorstatementis:

OnErrorResumeNext



Thisisreferredtoasinlineerrorhandling.Thefollowing

exampledemonstratesthistypeoferrorhandlingintheprocess



ofrenamingafile.Thecodespecificallyexaminesanyerror

number(Err.Number)generatedbytheRenamefunction.

DimoldNameAsString

DimnewNameAsString

OnErrorResumeNext

'-----Prompttheuserfortheoldandnewnames.

oldName=InputBox("Enterthefilenametorename.")

newName=InputBox("Enterthenewfilename.")

'-----Renamethefile.

Err.Clear()

Rename("c:\"&oldName,"c:\"&newName)

'-----Dealwithanyerror.

If(Err.Number=53)Then

'-----Filenotfounderror.

MsgBox("File'"&oldName&"'notfound.")

ExitSub

ElseIf(Err.Number<>0)Then

'-----Allothererrors.

MsgBox("Error"&Err.Number&":"&Err.Description)

ExitSub

EndIf



Centralizederrorhandling.Centralizederrorhandlingkeeps

errordetectionanderrorhandlinginthesameprocedure,butit

placesallerror-handlingcodeinacommonlocationwithinthat

procedure.Thisisespeciallyusefulwhencodedetectionfora

commonsetoferrorsoccursmultipletimesthroughoutalarge

procedure.Executionisredirectedtothecentralerror-handling

codeblockusingthestatement:



OnErrorGoTolabel



Thisisoutlinedinthefollowingcodetemplate:

PublicSubExample()

OnErrorGoToErrorHandler

'-----Ifarun-timeerroroccurshere,VisualBasic

'directsexecutiontotheErrorHandlerlabel.

ExitSub

ErrorHandler:

'-----Codecanbeplacedheretohandleerrorsdirectly.

'Err.Number,Err.Description,andErr.Sourcecanbe

'examinedhere.

EndSub



OncetheOnErrorGoToErrorHandlerstatementisexecuted,the

errorhandlerbeginningatthelabelErrorHandlerisactive.There

areseveralpossibilitiesfordealingwiththeerror.Themost

commonpossibilityissimplytohandletheerrorintheactive

errorhandler,perhapsbydisplayinganerrormessageasking

theusertotakecorrectiveaction.

Anothercommonapproachistopassinformationaboutanerror

tothecallingprocedurethroughparametersorthroughthe

returnvalueoftheoffendingfunction.Forinstance,ifafunction

isdesignedtorenameafile,thefunctionmightreturnan

integererrorcodeindicatingthesuccessorfailureofthe

operation.ThismethodisquitecommonamongtheWin32API

functions.Inparticular,theerrorcodemightbe0forsuccess,

-1ifthefiledoesnotexist,-2ifthenewfilenameisinvalid,and

soon.



Athirdpossibilityistopasstheerrortothecallingprocedureby

invokingtheErr.Raisemethodwithintheactiveerrorhandler:

Err.Raise(Err.Number,Err.Source,Err.Description,_

Err.HelpFile,Err.HelpContext)



Thistriggersthenextprocedureupinthecallstacktoprocess

theerrorusingitsownactiveerrorhandler.Thisprocessis

calledregeneratingorreraisingtheerror.Ifthatproceduredoes

nothaveanactiveerrorhandler,theraisederrorcontinuesup

thecallstackuntilitfindsaprocedurewithanactiveerror

handler.

Noenablederrorhandler.Whenyoufirstenterany

procedure,errorhandlingisdisabledinthatprocedureuntilthe

codeencounterssomesortofOnErrororstructuredexceptionhandlingstatement.UsingOnErrorGoTolabelenablescentralized

errorhandling,butwhatifyouwanttoturnoffthecentral

error-handlingblockcode?Thefollowingstatementtakesjust

suchanaction,restoringtheerror-handlingstatetowhatitwas

whenyoufirstenteredtheprocedure.

OnErrorGoTo0



Withoutanenablederrorhandler,allerrorscauseexecutionto

moveupthecallstacktothenextprocedure,continuingup

untilanenabledexceptionhandlerisfound.Alackofexception

handlerscausesVisualBasictodisplayanerrormessageand

terminatetheapplication.

AthirdvariationoftheOnErrorstatementdisablesanerror

handlerfrominsideofanerrorhandler:

OnErrorGoTo-1



Thisstatementcanbeusedwithinablockoferror-handling

code.Itcausestheproceduretoforgetthatitisinanerror

handler;Resumestatementswillhavenoimpactafterusingthis

statement.Toreinstateerrorhandling,youmustuseanotherOn

Errorstatement.

Newin2005.VisualBasic2005addssupportforaglobal,

centralerror-handlingroutine.Thisfeatureisonlyavailablein

WindowsFormsapplications,anditisaccessedthroughthe

My.Application.UnhandledExceptionevent.Theactualprocedure

forthiseventisfoundintheapplication'sApplicationEvents.vb

file,whichishiddenfromtheSolutionExplorerviewbydefault.

(ClicktheShowAllFilesbuttonintheSolutionExplorerto

displaythisandotherhiddenfiles.)Theeventprocedurehas

thefollowingform.

NamespaceMy

ClassMyApplication

PrivateSubMyApplication_UnhandledException(_

ByValsenderAsObject,_

ByValeAsUnhandledExceptionEventArgs)_

HandlesMe.UnhandledException

'-----Specialerrorhandlingcodegoeshere.

EndSub

EndClass

EndNamespace



Thisspecialeventhandlerisignoredwhenrunningyour

applicationwithintheVisualStudioIDE.



11.2.2.StructuredExceptionHandling



StructuredexceptionhandlingusestheTRy...Catch...Finally

constructtohandlelocalerrors.Thisisamuchmoreobjectorientedapproach,involvingobjectsoftheSystem.Exception

classanditsderivedclasses.

Thesyntaxofthetry...Catch...Finallyconstructis:

Try

tryStatements

[Catch[exception[Astype]][Whenexpression]

catchStatements

[ExitTry]]

[Catch[exception[Astype]][Whenexpression]

catchStatements]

...

[Catch[exception[Astype]][Whenexpression]

catchStatements]

[Finally

finallyStatements]

EndTry



ThetryStatements(whicharerequired)constitutethetryblock

andarethestatementsthataremonitoredforerrorsbyVB.

Errorhandlingisactivewithinthetryblock.

TheCatchblocks(youcanincludezeroormoreofthese)contain

codethatisexecutedinresponsetoVB"catching"aparticular

typeoferrorwithintheTRyblock.Thus,theCatchblocksconsist

oftheerrorhandlersfortheTRyblock.

Theexception[Astype]and[Whenexpression]clausesarereferredto

asfilters.Anexceptioniseitheravariableoftype

System.Exceptionoroneofitsderivedclasses.Itisbyusing



oneofthesederivedclassesthatyoucannarrowthescopeofa

Catchclausetoaspecificerror.Theclause:

CatchexAsException



willcatchanyexceptionforhandlingwithinthatCatchblock.The

clause:

CatchexAsDivideByZeroException



catchesdivide-by-zerodivisionerrors,butnoothers.The

DivideByZeroExceptionclassisoneoftheclassesderivedfrom

System.Exception.

TheWhenfilteristypicallyusedwithuser-definederrors.For

instance,thecodeinthefollowingTRyblockraisesanerrorif

theuserdoesnotenteranumber.

DimuserInputAsString

Try

userInput=InputBox("Enteranumber.")

IfNotIsNumeric(userInput)ThenErr.Raise(1)

CatchWhenErr.Number=1

MsgBox("Supplieddatawasnon-numeric.")

EndTry



Thefollowingcodewillnotcatchanerror,sincenotrueerroris

generated:

DimtestNumberAsInteger

Try

testNumber=5



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

Chapter 11.  Error Handling in Visual Basic

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

×