48
ErrorChecking
Logicerrorsareerrorsthatthecomputercannotspot. Theseareerrorsthat,eventhough
theprogramruns,theresultisnotwhatyouintended.
Thefirsttwooftheseerrorsaregenerallyeasytospot,andthedebuggingtoolcanbeused
tohigh-lighttheline oftextatwhichtheerroroccurred. For r example,ifyouwantedto
makeaprogramtoconvertCelsiustoFahrenheit,andinthecodeyouusedamultiplication
symbolinsteadofdivision,theprogramwouldrunfine,buttheprogramwouldnotconvert
thetemperaturescorrectly,asyoudesired. Althoughsometimes s theselogicerrorscanbe
easy tospot,somearequite difficult. Logicerrorsbecomeconcealedinthelinesofcode
whenmakingcomplexprograms,suchasagame. Justremember,thecomputerdoes s not
knowwhattheprogramissupposedtodo,itonlyknowsthecode. Lookthroughthecode
step-by-stepandthinkofhowthecomputerwouldinterpretthecode.
VBwon'tletyoujustignoresyntax/compileerrors. Youhavetofixthembeforeyoucan
runyourprogram. Butrun-timeerrors,whicharesyntacticallycorrect,butmaycausean
errorifanattemptismadetoexecuteit,canbehandledtopossiblypreventyourprogram
fromcrashing.Thefollowingexampleshowsaverygoodwayofhandlingapossibleerror:
Private Sub Form_Load()
On Error r GoTo ErrorHappened
i = = 1 / 0 'This line e will l cause an n error r to be e raised as s anything g divided
by zero = infinity
'...
'Some code
Exit Sub b 'Here e the subroutine is exited d if f no errors occur
ErrorHappened:
'Informs the e user an n error r happened.
MsgBox "Error Number r " " & Err.Number & ":" & Err.Description
End Sub
The output ofthis example is amessage box that says "Error Number 11: Divisionby
zero". ThestatementOnErrorGotoErrorHappenedwillskipeverythingfromi i = = 1 1 / / 0
toExit Subifanyrun-timeerroroccurswithinthisprocedure.Whenanerrorisdetected
theprogramwillcontinuetorunfromrightafterErrorHappened:,wheretheerrorwillbe
displayedsothattheprogrammercanfindoutwhatitisandfixit.Thisalsopreventsthe
programfrom"crashing".
ErrorHappened is s just t a line label, , you u canname it t anythingyou u wish to identify y that
sectionof the procedure e you u want to o execute when n an error happens. On n Error r Goto
canonlyreferenceline labelsthat arewithinthecurrent procedure. Youcannot(easily)
defineoneerrorhandlerforallprocedures. ExitSubmeanstoendtheForm_Loadevent
immediately.
Soifnoerroroccurs,amessageboxwillNOTbecalledbecauseExitSubwillalreadyhave
endedorexitedoursubroutine. Andifanerrordoesoccur,themessageboxwillpopup,
displayingtheErrorNumberandtheErrorDescription.
Theaboveexampleisthesafestwayofdetectingandhandlinganyerrorthattakesplacein
thesubroutine. Howeveryoucanalsochoosetoignoreerrorsbyusing"OnErrorResume
Next"whichmeanstoignoreallerrors.Ignoringerrorsisnotagoodideainmostscenarios,
butinsomecasestheproperwaytohandleanerroristodonothing,sotheymightaswell
beignored. EvenusingResumeNext,youcantesttheErrobject(Err.Number)toseeif
anerrorhappenedonprecedinglines.
19