Вы находитесь на странице: 1из 32

Error handling

Using XL’s objects

Giovanni Zucchinetti
giovanni.zucchinetti@gitec.ch

Adapted from the course « Notions informatiques – Modèles de calcul »


with kind permission from Prof. Yves Pigneur and Dr. Gabor Maksay

HEC Lausanne
Computanional Tools for Actuaries (CTA)
Agenda

1. Error handling
2. More on Objects
3. Working on Excel’s objects
Error handling

HEC Lausanne
Computanional Tools for Actuaries (CTA)
Errors
• All code contains errors of one kind or another and how you deal
with errors may be the most important part of a well-designed
application.

• There are two categories of errors : those you can prevent, which
are called development errors, and those you can't prevent but can
trap, which are called run-time errors.

CTA - G. Zucchinetti 4
Syntax & logic errors
• Development errors are either syntax errors or logic errors.
Syntax errors occur from typographical errors, missing
punctuation, or improper use of a language element; for
example, forgetting to properly terminate an If…Then…Else
statement.
• Logic errors are more commonly referred to as "bugs”.
These errors occur when code executes without causing an
error, but does not produce the results intended. You eliminate
development errors by "debugging" your code. There are a
wide variety of tools that can help you debug script and Visual
Basic for Applications (VBA) code.

CTA - G. Zucchinetti 5
Run-time errors
• Run-time errors are errors that occur while the application is
running. These are errors where otherwise correct code fails due to
invalid data or system conditions that prevent the code from
executing (for example, lack of available memory or disk space).
• You handle run-time errors by writing error handlers and by writing
procedures that can validate program or environmental conditions in
appropriate circumstances.
• Writing good error handlers is a matter of anticipating problems or
conditions that are beyond your immediate control and that will
prevent your code from executing correctly at run time. Writing a
good error handler should be an integral part of the planning and
design of a good procedure.

CTA - G. Zucchinetti 6
Examples

• Single line syntax error

• Compile time error

• Logic error

• Runtime error

CTA - G. Zucchinetti 7
Dealing with runtime errors
• Error (or exception) handling is the process of responding to the
occurrence, during computation, of exceptions – anomalous or
exceptional situations requiring special processing – often changing
the normal flow of program execution. It is provided by specialized
programming language constructs or computer hardware
mechanisms.
• In general, an exception is handled (resolved) by saving the current
state of execution in a predefined place and switching the errors to a
specific subroutine known as an exception handler. If exceptions are
continuable, the handler may later resume the execution at the
original location using the saved information.
• For example, a floating point divide by zero exception will typically, by
default, allow the program to be resumed, while an out of memory
condition might not be resolvable transparently.

CTA - G. Zucchinetti 8
What if you don’t handle errors
• If you have no error handling code and a run time error occurs,
VBA will display its standard run time error dialog box and stop
running.
• While this may be acceptable, even desirable, in a
development environment, it is not acceptable to the end user
in a production environment.
• The goal of well designed error handling code is to anticipate
potential errors, and correct them at run time or to terminate
code execution in a controlled, graceful method. Your goal
should be to prevent unhandled errors from arising.

CTA - G. Zucchinetti 9
Error handling : 3 steps
• Identify where an error might occur

• Identify the type of the error

• Decide what to do

CTA - G. Zucchinetti 10
« Risky » situations
• File access

• User input

• Hard to anticipate / prevent situations

• Sometimes testing if you generate an error is an easy way of


performing some actions

CTA - G. Zucchinetti 11
VBA : On Error Goto LineLabel
Enables the error-handling routine that starts at line specified in the
required line argument. The line argument is any line label or line
number. If a run-time error occurs, control branches to line, making the
error handler active. The specified line must be in the same procedure
as the On Error statement; otherwise, a compile-time error occurs.
Example :
Sub SignTopCell()
On Error GoTo NoWorksheet 'if an error happens, jump out of the routine
Worksheets("Test").Select 'now try going to worksheet (may trigger error)
Range("A1").Value = ”Hello” 'if we get here, the worksheet did exist –
Exit Sub 'so sign it and leave
NoWorksheet: ‘line label
'if we get here, the worksheet didn't exist -
MsgBox "No such worksheet!” 'display error message
End Sub

CTA - G. Zucchinetti 12
On Error Resume Next
• Specifies that when a run-time error occurs, control goes to
the statement immediately following the statement where the
error occurred where execution continues.
Example :
On Error Resume Next
 N = 1 / x ' cause an error when x = 0
 If
Err.Number <> 0 Then 
 N = 1
 End If

• If you don’t check for the error number after the division, the
program will not fail (because of the error trapping), but N
would not be defined. So it may be dangerous to use « on
error resume next » without any action

CTA - G. Zucchinetti 13
Err Object
• Error-handling routines rely on the value in the Number property of
the Err object to determine the cause of the error.
• The error-handling routine should test or save relevant property
values in the Err object before any other error can occur or before a
procedure that might cause an error is called.
• The property values in the Err object reflect only the most recent
error.
• The error message associated with Err.Number is contained in
Err.Description

• Error number / description list :


http://support.microsoft.com/kb/146864

CTA - G. Zucchinetti 14
Resume line
• Execution resumes at line specified in the required line argument.
The line argument is a line label or line number and must be in the
same procedure as the error handler.
• Useful in order to « rebranch » after error handling
Sub SignTopCell()
On Error GoTo NoWorksheet
Worksheets("Test").Select
Range("A1").Value = ”Hello”
Procedure_End: ‘line label
’any cleanup code
Exit Sub leave
NoWorksheet: ‘line label
'if we get here, the worksheet didn't exist -
MsgBox "No such worksheet!”
Resume Procedure_End
End Sub

CTA - G. Zucchinetti 15
On Error GoTo 0
• On Error GoTo 0 disables error handling in the current
procedure. It doesn't specify line 0 as the start of the error-
handling code, even if the procedure contains a line
numbered 0. Without an On Error GoTo 0 statement, an error
handler is automatically disabled when a procedure is exited.
• The system reverts to the default error-handling (ie displaying
a system error message, and stopping the program).

CTA - G. Zucchinetti 16
Objects : extending the example

HEC Lausanne
Computanional Tools for Actuaries (CTA)
Object properties
• If an object is supposed to refer or to contain another object, you
can define object properties
• Object properties can either be defined as Class Module level public
variables (ex : Public boss As CEmployee) , or through Set /
Get property procedures
• The Property Set procedure behaves like the Property Let
procedure, except that you use it to assign an object reference to an
object property. A corresponding Property Get procedure returns
the object reference.
Private pBoss As CEmployee
Property Set boss(theBoss As CEmployee)
‘Some consitency checks
Set pBoss = theBoss
End Property
Property Get boss() As CEmployee
Set boss = pBOSS
End Property
CTA - G. Zucchinetti 18
Assigning objects
• The Set statement assigns an object reference to a variable or property.
- Set emp.boss = theChief
- Set theEmployees(currentID).boss = theEmployees(theBossID)
• Generally, when you use Set to assign an object reference to a variable, no
copy of the object is created for that variable. Instead, a reference to the
object is created. More than one object variable can refer to the same
object.
• Because such variables are references to the object rather than copies of
the object, any change in the object is reflected in all variables that refer to
it.
• However, when you use the New keyword in the Set statement, you are
actually creating an instance of the object.
• When New is used with Set, it creates a new instance of the class. If the
variable contained a reference to an object, that reference is released when
the new one is assigned.

CTA - G. Zucchinetti 19
Dim emp as CEmployee

emp

CTA - G. Zucchinetti 20
Set emp = New CEmployee

emp
CEmployee inst1
ID
Name
Salary
Boss

CTA - G. Zucchinetti 21
emp.ID = "d1"

emp
CEmployee inst1
ID “d1”
Name
Salary
Boss

CTA - G. Zucchinetti 22
Dim emp2 as CEmployee

emp
CEmployee inst1

emp2 ID “d1”
Name “Paul”
Salary 80000
Boss

CTA - G. Zucchinetti 23
Set emp2 = emp

emp
CEmployee inst1

emp2 ID “d1”
Name “Paul”
Salary 80000
Boss

CTA - G. Zucchinetti 24
Set objectVar = Nothing
Discontinues association of objectvar with any specific object.
Assigning Nothing to objectvar releases all the system and
memory resources associated with the previously referenced
object when no other variable refers to it.
- Set emp = Nothing

CTA - G. Zucchinetti 25
Set emp = Nothing

emp
CEmployee inst1

emp2 ID “d1”
Name “Paul”
Salary 80000
Boss

CTA - G. Zucchinetti 26
Set emp2 = Nothing

emp

emp2

CTA - G. Zucchinetti 27
Set emp.boss = emp4 CEmployee inst1
ID “d1”
Name “Paul”
Salary 80000
emp Boss

emp4
CEmployee inst4
ID “d4”
Name “Mark”
Salary 140000
Boss
CTA - G. Zucchinetti 28
CEmployee inst1
Collection : theEmployees
ID “d1”
theEmployees Name “Paul”
Salary 80000
Boss
emp4

CEmployee inst4
Collection c1 ID “d4”
1 Name “Mark”

Salary 140000

Boss
4
CTA - G. Zucchinetti 29
Call theEmployees.Add(emp4,emp4.id) CEmployee inst1

ID “d1”
theEmployees Name “Paul”
Salary 80000
Boss
emp4

CEmployee inst4
Collection c1 ID “d4”
1 Name “Mark”

Salary 140000

Boss
4
CTA - G. Zucchinetti 30
Example - Error handling, Object
property, Collection
See XL + VBA file

CTA - G. Zucchinetti 31
References
• [Maksay 08] Maksay Gabor, Pigneur Yves, Modéliser par l'exemple, Presses
polytechniques et universitaires romande, 2008,
http://www.ppur.org/produit/290/9782880748951/Modeliser%20par%20lexemple
%20

• [Seref 07] Michelle M.H. Şeref, Ravindra K. Ahuja, and Wayne L. Winston ;
Developing Spreadsheet-Based Decision Support Systems Using Excel and VBA
for Excel ; Dynamic Ideas, Belmont, Massachusetts 2007

• [Hainault 02], Jean-Luc Hainault, Bases de données et modèles de calcul (3ème


édition), Dunod, 2002

CTA - G. Zucchinetti 32

Вам также может понравиться