Publications: 83 | Followers: 0

Exceptions & Error Handling - Temple University

Publish on Category: Birds 0

Exceptions & Error Handling
Christopher M. Pascucci
Errors and Exceptions
Anerroris a bug in yourprogram.dividing by zerogoing outside the bounds of an arraytrying to use anullobject or referenceAnexceptionis a problem whose cause is outside yourprogram.trying to open a file that isn’t thererunning out ofmemoryconnecting or working with a database and SQL
What to do about errors and exceptions
An error is a bug in yourprogram that occurs during execution of program code.It should befixed.An exception is a problem that your program mayencounter.The source of the problem is outside yourprogram.Yourprogram must be prepared to deal withit.The distinction between the two is that an error is an event and an exception is an object that was created by the event that contains where and when the error occurred.
Dealing with exceptions
Most exceptions arise when you are handlingfiles or working with databases.A needed file may bemissing.You may not have permission to write adatabase or file.A file or field may be the wrong type.Exceptionsmay also arise when you use someone else’s classes (or they use yours).You might use a classincorrectly.Incorrectusageshould result in anexception.
Three approaches to error checking
Ignore all but the most importanterrors.The code is cleaner, but the program will misbehave when it encounters an unusualerror.Do something appropriate for everyerror.The code is cluttered, but the program worksbetter.You might still forget some errorconditions.Do the normal processing in one place, handle the errors in another(this is the.NETway).The code is at least reasonablyuncluttered..NETtries to ensure that you handle everyerror.
.NETprovides acontrolstructure, theTrystatement (also called theTry-Catchstatement) to separate “normal” code from error handling:Trytry this code and if an error occurs during thiscode it will be handled in the catch.Catchsome exceptionhandle the exceptionCatchsomeotherexception (***optional)handle the exceptionFinallyOptional code block that always executes after the try-catchWhether or not an exception occurred.End Try
Exception handling isnotoptional
As in other languages,errorsusually just cause your program tocrash.Other languages leave it up to you whether you want to handleexceptions.There are a lot of sloppy programs in theworld.It’s normal for human beings to belazy..NETtries toforceyou to handleexceptions.This is sometimes a pain in the neck,but...the result is almost always a betterprogram.
Whenanerroroccurs,.NETthrowsanExceptionand creates anExceptionobject for you to use.You cancatchthis objectandtry torecover.You canignorethe error (the program will crash)..NET also provides a global Err object that can be used like in previous versions of VB.Err.number– displays the error number.Err.Description– displays the error message.
A fewcommon typesof Exceptions
IO.IOException: a problem doinginput/output.IO.FileNotFoundException: no suchfile.IO.EndOfStreamException: tried to read past theendof an i/o stream.NullReferenceException: tried to use a object that was actuallynull(this is aRuntimeException).InvalidCastException: tried to convert a non-numeric String to a numberor some other invalid casting.IndexOutofRangeException: tried to access an array element using an index that is outside the bounds of an array.Data.DataException: error generated by using ADO.NET components.Data.SqlClient.SqlException: error generated by an SQL server.ArgumentException: generated when at least one of the arguments past to a method is not valid.
What to do about Exceptions
You havethreechoices:You candeal with it at the Page levelusingTry-Catchthrough out the pageusing thePage_Errorevent of the pageYou candealwithit at the Application levelusing theApplication_Errorprocedure in theglobal.asaxfile.You can deal with it in thecustomErrorsection of theweb.configfile.<customErrorsmode="On"defaultRedirect="myerror.htm"><errorstatusCode="403"redirect="authfailed.aspx"/><errorstatusCode="404"redirect="filenotfound.aspx"/></customErrors>
After all the catch phrases, you can have anoptionalFinallyphrase.TryCatcheasExceptionTypeCatcheasAnotherExceptionTypeFinallyEnd TryWhatever happens inTryandCatch,even if it does aReturnstatement,theFinallycode will beexecuted.If no exception occurs, theFinallywill be executed after theTrycode.Ifan exception does occur, theFinallywill be executed after the appropriateCatchcode.
How theTrystatement works
The code in theTryblockpartisexecuted.If there are no problems, theCatchphrases areskipped.If an exception occurs, the program jumpsimmediatelyto the firstCatchclause that can handle thatexception.Whether or not an exception occurred, theFinallycode isexecuted.
Ordering theCatchphrases
ATrycan be followed by manyCatches.The first one thatcancatch the exception is the one thatwillcatch theexception.Bad:CatcheAs ExceptionCatcheAsIO.IOExceptionThis is bad becauseIOExceptionis a subclass ofException, so anyIOExceptionwill be handled by thefirstCatch.The secondCatchphrase can never beused.Start by orderingCatches from the more specific down to the more general.
Constructing anException
Exceptions are classes; you can create your ownExceptionwithnew.Exception types have two constructors: one with no parameters, and one with aStringparameter.Butfirst, you should look through the predefined exceptions to see if there is already one that’sappropriate.
TryThrow NewNotEnoughPizzaException(_"Better order more")CatchexAsNotEnoughPizzaExceptionResponse.Write(ex.Message)End Try
Public ClassNotEnoughPizzaExceptionInheritsSystem.ApplicationExceptionPublic SubNew()End SubPublic SubNew(ByValstrMessageAs String)MyBase.New(strMessage)End SubEnd Class
Additional Resources:Exception HierarchyComprehensive List of Exceptions & Hierarchy





Make amazing presentation for free
Exceptions & Error Handling - Temple University