Exception/Error Handling, An Integral Part of Programming

Exception handling is an essential part of theThe name of the routine in which the exception
programming experience, it polishes the applicationoccurred.
and is a bulwark against somewhat forgivableLine number. If available the code line number or last
oversight. We most likely will not cover everydeclared line number when the exception occurred.
situation in the first build of an application but at leastThis can really help pin point the line of code the
we can include the ability to handle unforeseenexception occurred within.
runtime exceptions and build some useful tools utilisingClass or module name. This helps locate the code
exception systems to help with the applicationthat threw the exception.
development process.CUSTOM EXCEPTIONSCall stack: This can be useful to trace the series of
=================Custom built exceptions areevents prior to the exception.
a handy tool for both release and developmentActive controls or forms: The current active control
versions of an application. They can be used in theand/or form which could give a clue as to what the
following ways:Custom Exceptions as Developeruser was trying to do when the exception occurred,
Warningsalthough the call stack could cover this instead.
---------------------------------------We can use exceptionsSource of the exception: Perhaps the exception was
to remind us of not providing requisite information tocaused by an application interactivity or
a class or object. For example: We build a class as aninteroperability.
interface to multiple vendor databases, let's call itTime of the exception: Maybe the user went to
Multiple Vendor Management (MVM) class. To connectlunch before reporting the exception. It may help to
to a particular database we perforce provide theknow that when the exception occurred there was a
instantiated MVM class with the vendor databaseconcurrent hiatus of intranet connectivity.
type we are connecting to via a database_typeUser explanation: An explanation for the user on
method within the class. The MVM class also has ahow the exception impacts their ability to carry out
SQL_select method that can be called to return atheir tasks. It probably is not necessary to confuse
recordset from our chosen vendor database. Withinthe user with exactly what went wrong, just that
the SQL_select method is a switch (select case)the application can not perform their task at the
statement which decides how to send the 'selectpresent time.HANDLING HIDDEN ASSUMPTIONS
request' to our chosen database type. If we fail to===========================As a rule I
provide the vendor database type to our class andput exception handling into almost every routine to
call the SQL_select method at runtime or a debugneutralise the spectre of the hidden assumption. I am
compilation, a default (case else) option within ourcurrently working with a business process
switch (select case) statement throws a customdiagramming application in which there are scripted
exception for developers. The custom exception willreports. One particularly critical report every now and
remind a developer during runtime testing that thethen can not complete it's processing, this is a legacy
requirements of the class have not been fulfilledreport which has code that makes inadequate use of
during our coding. Below is an example of where ourexception handling. Every time the report stops I
custom exception can be used:Private Subdiagnose the problem as missing Lane symbol names
SQL_select(SQL As String)dim exp_developer_1 aswithin the diagram the report is trying to process.
RuntimeExceptionThe developer who had scripted the report
exp_developer_1 = new RuntimeExceptionmistakenly assumed that there would always be a
exp_developer_1.Message = "'database_type'name attributed to a Lane symbol, but when a user
property is not set."forgets to enter a Lane symbol's name, the report
exp_developer_1.ErrorNumber = -90000dim rs Asstalls and has no way to handle the exception that is
RecordSetselect case database_typecasethrown. The hidden assumption is: A Lane symbol has
MySQL_DATABASEa name property therefore there is a name value
if Connect_mysql thenavailable within that property. Of course the
rs = mysql.SQLSelect(SQL)developer and client most likely tested the report
end if // Connect_mysqlcase ODBC_DATABASEagainst well formed diagrams before releasing the
if Connect_odbc thenfirst build so the exception was never thrown during
rs = odbcdb.SQLSelect(SQL)testing. This is not really any party's fault but the
end if // Connect_odbccase REAL_DATABASEresult of human fallibility that has not been catered
if connect_rbdb thenfor by utilising exception handling.EXCEPTION
// replace any instance of the word DISTINCT withLISTENER
UNIQUE to cater for RBDB syntax.==================Instead of building a
SQL =central exception handler to provide exception
Replace_passed_regex_strings(SQL,"sDISTINCTs","notification or central exception reporting we could
UNIQUE ")create an class that captures exceptions and
rs = rbdb.SQLSelect(SQL)performs functions based upon the type of
end if // Connect_rbdbcase elseexceptions it receives. One function might be to
Raise exp_developer_1end selectExceptioncapture exceptions into a collection and provide
errd=New MessageDialogadvice to calling routines as to what kinds of services
if err = exp_developer_1 thenthe application can provide the user at any one time,
d.Set_Icon_Caution_Trianglefor example: We have an application that accesses
elseseveral diverse data sources which upon start up fails
d.Set_Icon_Stopto connect to one of it's data sources and throws an
end ifd.ActionButton.Caption = "OK"#if TargetWin32exception. The exception is handled and passed to
or TargetLinux Thenthe Exception Listener. From now on any event that
//ERR_MODULE is a constant that holds theopens a form can call the Exception Listener to see if
module's/form's name + a full stopany details the form provides the user are
d.Title = ERR_MODULE + "SQL_select"if err =inaccessible and as a result can disable controls that
exp_db_error thenallow the editing or reading of those details. The
d.Message = d.ERROR_NUMBER_TEXT +latter scenario would allow the user to still perform
cstr(exp_db_error.ErrorNumber) + _some duties although in a limited way, which is better
EndOfLine + d.ERROR_DESCRIPTION_TEXT +than not allowing the user to do any work and may
exp_db_error.Message 'messagestill enable the user to finish their work tasks with the
elsed.Message = d.ERROR_NUMBER_TEXT +limited functionality provided. When I say limited
cstr(err.ErrorNumber) + _functionality we could be speaking of only a minor
EndOfLine + d.ERROR_DESCRIPTION_TEXT +disruption to functionality overall.Another benefit of
err.message 'messagean Exception Listener could be the ability to
end ifperiodically check the collection of exceptions it holds
#else//ERR_MODULE is a constant that holds theand try to resolve the original cause of the
module's/form's name + a full stopexceptions. In the example above where our
d.Message = d.ERROR_ROUTINE_TEXT +application could not access a data source, the
ERR_MODULE + "SQL_select" + EndOfLineException Listener could thread a retry of the
if err = exp_db_error thenconnection whilst the application is running and upon a
d.Message = d.Message + d.ERROR_NUMBER_TEXTsuccessful connection notify it's clients of the
+ cstr(exp_db_error.ErrorNumber) + _availability of details from the data source again and
EndOfLine + d.ERROR_DESCRIPTION_TEXT +remove the exception from the collection. This is
exp_db_error.message 'messagebetter than the user having to save what they are
elsed.Message = d.Message +doing, close the application and reopen it to
d.ERROR_NUMBER_TEXT + cstr(err.ErrorNumber) +reconnect to a previously inaccessible data source.If
_our Exception Listener was a software bus it could
EndOfLine + d.ERROR_DESCRIPTION_TEXT +publish any messages to it's subscribers within the
err.message 'messageapplication and we could have a real-time release of
end iflimited functionality within forms, web pages and
#endifd.AlternateActionButton.Caption = "Details toother interfaces.Statistical Analysis of Application
Clipboard"Functionality
d.AlternateActionButton.Visible = True-------------------------------------------------Statistical analysis
b=d.ShowModalSelect case bof the amount of functionality that can be provided
case d.ActionButtonby an application can also be published by the
case d.AlternateActionButtonException Listener where a missing data source may
d.Details_to_clipboardcase d.CancelButtonbe determined to reduce the application's functionality
end selectfinallyby 25%. The user can be notified that the application
// clean upis only 75% functional which would be useful
if dNil then d=Nilinformation in a unstable environment. The
return rspercentage of functionality would rise or fall based
End SubCustom Exceptions used for Call Stackupon exception resolution and exceptions thrown
Retrocessionrespectively.Exception Cluster Explanation
--------------------------------------------------A custom-----------------------------With a collection of exceptions
exception could be used to create a call stack (within the Exception Listener we could abstract out a
break out scenario. For example, we have ancomprehensive explanation of what an application's
application that is six calls down a call stack ofcurrent capabilities and limitations are by diagnosing
database transaction routines and a critical data errorclusters of various exceptions and/or exception
has occurred. Instead of handling the exception,types. When a user tries to perform a task and
exiting the routine and allowing the parent routine toreceives an exception the notification of the
continue processing it's database transactions we useexception could provide the ability to open an
a custom exception to roll back all calls within the callexplanation dialogue instead of only providing the
stack and their transactions. We throw the customability to dismiss the exception notification. The
exception within the current routine whose exceptionException Listener could provide a comprehensive
handler rolls back our current routine's databasereport upon current application limitations that are
transactions and then throws the custom exceptionproducing current system behaviour. For example,
again within the exception handling section of oureven though our application may have successfully
routine's code. The exception handler in our currentconnected to an Account system we cannot retrieve
routine cannot handle the newly thrown customa staff member's salary transactions because our
exception so transfers control back up the call stackapplication cannot access the necessary employee
to the previous routine. The previous routine handlesidentification details on a Human Resources system
the custom exception in the same way, and so onthat is offline. Throwing an exception that informs
until we reach the top of the stack, having rolledthe user that an accounts routine can not perform its
back all routines' database transactions. The initiatingtask does not explain why this has happened and the
routine of the stack can then report the exceptionuser will most likely contact the help desk for the
or, the routine that caught the first exception couldexplanation, whereas a comprehensive explanation
report the exception (see heading Exceptionfrom the Exception Listener which explains the
Notification Detail further on in article for why weeffects of a Human Resources system being offline
would do this) and then start the retrocession of thecould instantly explain why the accounts routine is
stack.Custom Exception Genericsfailing the user.SUMMARY
--------------------------Custom exceptions do not need=======Exception handling is an integral and
to be specific in their reporting detail, they aresometimes unappreciated part of any programming
custom built so we can change their messages toregimen. Points covered were:Custom exceptions help
better fit the circumstance in which we want towith the development process using custom
throw the exception. For instance, say we have adeveloper exceptions to remind developers of missed
custom database exception:dim exp_db_error asrequirements during coding.
RuntimeExceptionCustom exceptions can retrocede through a call
exp_db_error.number = -10001stack and rollback prior transactions and processes.
exp_db_error.message = "Database file can not beExceptions can handle the scripting of our hidden
found."We raise this exception within a routine whereassumptions.
the database file is found but is corrupt, we canException Listeners can provide the ability to limit
change the message to better fit the circumstanceservices within an application allowing the user to
of the exception:exp_db_error.message = "Databaseperform tasks albeit some functionality will be
file is corrupt."disabled.
Raise exp_db_errorThe exception number relates toException Listeners can provide comprehensive
database specific issues but the message the userexplanations of limited application behaviour and the
receives is more relevant to the situation than apossible cause of thrown exceptions.
generic exception message.EXCEPTIONException Listeners can provide a statistical
NOTIFICATION DETAILpercentage of application functionality.
=============================DetailsException Listeners can periodically try to resolve
provided in exception notifications perforce should beearlier exceptions that reduce a system's
useful to both the developer and the end user. Afunctionality.
basic exception-type number and description is usuallyException notifications can provide enough detail for
too vague or concise to be of use to either party.a developer or vendor to pinpoint the cause of an
What good is an exception notification thatexception in code whilst concurrently providing a
states:Exp No: 4026useful explanation to assuage user anxiety over an
Exp Desc: Index out of boundsAn exceptionexception.Duane Hennessy
notification needs to provide two types of usefulSenior Software Engineer and Systems Architect
information, diagnosis information for the developerBandicoot Software
or the vendor of the application and explanatoryTropical Queensland, Australia
information for the end user or the the vendor's(ABN: 33 682 969 957)Your own personal library of
client. Useful details to provide can be:Routine name.code snippets.