Tuesday, March 24, 2020

Chapter 5 Error Handling & Classes









Introduction
Errors occur even if we design an application carefully.  VB procedures don’t need error handling, sometimes files are mistakenly deleted, and disk drives run out of space, network drives disconnect unexpectedly; which causes run-time errors in code.

VB includes default error handler which presents a message with error number and a short description of that error and terminates the application which does not allow the user to save any work or close the application properly.  These errors are handled by using error handling codes.  Codes that handle run-time errors are called “error-handler”.

Types of Errors

Syntax Errors
Occur when we enter incorrect lines of codes.

Runtime Errors
Occurs when a command attempts to perform an action that is not valid.  This error occurs after the application starts execution.
Actions that generate runtime errors are:-

à    Writing to a non existing file.
à    Trying to select a table that has been closed.
à    Assigning a numeric variable to string.
à    Two users saving same record.
à    Dividing a number by zero.

Common Visual Basic Error Numbers are:-

5                      à        Invalid Procedure Call
6                      à        Overflow
7                      à        Out of Memory
9                      à        Subscript out of range
11                    à        Divide by Zero
13                    à        Type mismatch
53                    à        File not found
55                    à        File already open
58                    à        File already exists
76                    à        Path not found
423                  à        Property/Method not found
482                  à        Printer Error

There are three basic steps in creating an error handler:-

1)                  Enabling an error handler.
2)                  Writing code that can handle errors.
3)                  Continuing execution of program.

Logic Errors
Occurs when an application executes without syntax errors or run time errors.

Error Handler
Run-time errors can be handled by enabling an error handler with on Error Go to Statement.  The label identifies a point in code which the execution will branch when error encountered.  This section is named as ‘Error Handler’.

Error Handler is usually placed at procedure immediately after an Exit Sub Statement in the Program.  Following is the code for overflow of data:-

Private Sub Command1_Click ( )
On Error Goto Data.Err
Dim Num As Integer, Var as Integer
Num = 10
Var = Num * 10000
Print Var
Exit Sub
Data Err:
MsgBox “Try to Multiply with small numer”
End Sub

Err Object
Is used for notifying errors.  It contains information about runtime errors.  It enables us to determine which error occurred, its description and place.

Properties of the Err object are set by those who generate the error. i. e. Visual Basic or the programmer.  When run time error occurs its properties are filled with information that uniquely identify the error and required action to be taken to handle it.

Properties of Err Object

Number
Returns / Sets a numeric value to specify an error.  Number is the Err Object’s default property.  It is used to determine which error occurred.  Value of the property is unique number that corresponds to error condition.

Syntax:
Object.Number

Description
Returns / Sets expression containing a descriptive string associated with an error.
Syntax:
Object.Description
Source
Returns / Sets a string specifying the name application that generated the error.  When an unexpected error occurs in the code, source property is automatically set.
Syntax:
Object.Source

Help file
Returns / Sets a string containing path.
Syntax:
Object.Helpfile

Help Context
Returns / Sets a string containing the context Id for a topic in a file.
Syntax:
Object.HelpContext

Resuming Execution
There are three Resume Statements in Visual Basic.
Ø  Resume
Application Resume execution on the line of code that caused error.
Ø  Resume Next
Application resumes processing on the line of code following the line that caused the error.
Ø  Resume Line
Execution resumes at the point designated by the line label or the line number and must be in the same procedure as error handler.
Example
Private Sub Result_Click ( )
On Error GoTo Err1
Text3.Text = Text1.Text / Text2.Text
MsgBox “Error Resolved”
Exit Sub
Err1:
MsgBox Err.Number
MsgBox Err.Description
MsgBox Err.Source
If Err.Number = 11 then
Text2.Text = Text2.Text + 1
End If
Resume
End Sub

Methods of Err Object

1)                  Clear Method
Clears all properties or Err object after an Error has been handled.  This method is called automatically if we use Resume Statement, on Error Statement or when we Exit a Sub or function procedure.
Syntax:
Object.Clear
2)                  Raise Method
Used to generate an error.  It is useful for testing and evaluation.  We cause the error to be generated so that it can be handled by an error handler elsewhere in the program.
Syntax:
Object.RaiseNumber, Source, Description, Helpfile, Helpcontext.

Example:
Private Sub CmdError_Click ( )
Dim Num As Integer
Num = Val (Text1.Text)
On Error GoTo NoErr
Err.RaiseNum
Exit Sub
NoErr:
Select Case Err.Number
Case 6
MsgBox  “Data Overflow”
Text1.SetFocus
Case 11
MsgBox  “Division by Zero”
Text1.SetFocus
Case Else
MsgBox  “Error Not Known”
Exit Sub
End Select
Text1.Text =” “
End Sub

Trapping Errors
To handle errors efficiently we need to capture an error that occurs in a program called as trapping errors.  After the error is trapped we can take appropriate action based on the type of error and the decision that user takes.  Error trap is enabled when Visual Basic executes On Error Statement, which specifies an error handler.  Error trap is disabled on executing Exit Sub, Exit Function, Property, End sub, End Function or End Property etc for that procedure.  Error is disabled using On Error Goto 0.

Immediate Handling Errors
It causes the program to branch off to an error handling routine when error occurs.  “On Error GoTo Line” Statement indicates location of an error handling routine.  Error handler routine starts with a label, corresponding to the identifier specified in On Error GoTo Line.
In this method we need a statement immediately before error handling routine to exit the procedure that is Exit Sub.

Deferred Error Handling
In this method Visual Basic ignores the error when it occurs, but code checks the error later in the procedure.  The error handling code can be used to reset values of the variable which will enable the processing to continue.  This method can be invoked by using ‘On Error Resume Next’.  It prompts Visual Basic to continue with program execution after an error has occurred.
Example
Private Sub Command1_Click ( )
On Error Resume Next
Text3.Text = Text1.Text/ Text2.Text
If Err.Number> 0 Then
If Err.Number = 11 Then
Text3.Text =0
Else
MsgBox “Input is Invalid”
Exit Sub
End If
End If
End Sub

Creating Common Error Handling Procedure
When we add error handling code to an application, we notice that we are handling same errors over and over.  This can be reduced by writing few procedures that an error handling code can call to handle common error situations.  This reduces the code size.

Example:
Function Check ( )
Err.Raise900, , “No Blanks allowed”
Else
MsgBox “Record Saved”
End If
End Function

Private Sub Save_Click ( )
Call Check
End Sub

Classes
Class can be defined as a collection of code that forms a template for creating other objects in an application.  Three major principles required in a collection of objects are:-

1)                  Encapsulation
Information about an object like internal data and code is hidden.  Encapsulation isolates internal complexity of an object’s operation from the rest of the application.

2)                  Polymorphism
This implies the ability for various objects to have methods with the same name, but different content.

3)                  Inheritance
Ability of a sub class to take on the characteristics of different / parent class from which it is derived.  If characteristics of parent class change, sub class also inherits those characteristics.


Creating a Class
There are five steps for creating a class:-

1)      Adding a Class Module and selecting its properties.
2)      Creating properties of the class.
3)      Creating methods of the class.
4)      Creating events of the class.

Class Module
Class module contains definition of a class, including its property and method definitions.  Each class is created in special file with .CLS extension indicating that the code is the class module.

A standard module .BAS as file name extension and contains procedures and declarations commonly accessed by other modules within the application.

Adding a Class Module
To create a class we have to add a class module to our project by choosing ‘Add Class Module’ from Project Menu.

Creating Properties of the Class
Properties enables to pass data between a program and a class.  Properties in a class module can be created in two ways:-

à    Creating Public Variable.
à    Creating Property Procedure.
Public variable are created by using Public Keyword in Declaration Section of Class Module.
à        Public Ac_Num As Integer

This is simplest way of creating Property of a Class.  But it provides an open access to the information in the class.  Also using public variable does not enable us to create Read Only properties that are often required by a class.  Another alternate is to create Private variable, which can only accessed by code in the class module.

à        Private Ac_Num As Integer

Hence the recommended method would be to create procedures which enforce data hiding.  Ability to protect part of an object data while exposing rest of the data is called data hiding.  Visual Basic enables to create three types of property procedures.

1)                  Property Set
Only procedure that can not be created automatically with procedure dialog box.  It is used when the value passed to the procedure itself is an object.

2)                  Property Let
Specifies an argument that contains the value passed to the property.  Argument is passed by value to prevent procedure from changing the value of the variable passed to the procedure.

3)                  Property Get
Used to return value from the class.  To create a read-only property we create a Get Procedure omitting the Set and Let procedures.

Example:(Text to be displayed in Upper Case)

Dim GetCap As String
Public Property Get CapText ( ) As String
CapText = GetCap
End property

Public Property Let CapText (By Val NewCap As String)
GetCap = UCase(NewCap)
End Property

Private Sub Command1_Click ( )
Dim CS As Class1
Set CS = New Class1
CS.CapText = Text1.Text
Text1.Text = CS.CapText
End Sub

Where
Variable GetCap is used to hold text entered by user in the text box. 
Proerty Let procedure uses UCase function to convert text in Text Box to Upper Case.
Set CS = New Class1
This statement creates an object variable ‘CS’ of the class (Class1)
Property Set procedure takes an object as an argument.  Set keyword is used to assign the object to an internal object in the class.

Property Data Source Behavior
Used when we want an object to act as a source of data for other objects.  Set only at run time.
Syntax:
Object.DataSourceBehavipr[ =Number]

Parameter number is an integer specifies data source behavior according to settings:-

vbNone                       =          0          à Default Object can not act as data source.
vbDataSource            =          1          à Object can act as data source.

When data source behavior is set to 1 the Get Data Member event is added automatically.
Syntax:
Private Sub Object_GetDataMember (Data Member As String, Data As Object)

Where

DataMember Is a String containing the name of the data member to be bound as a data source.
Data Is a reference to Recordset object or a class.
We can add code to GetDataMember event procedure to select data from a data source within an object.
Following is the code, selects customer table as data member to retrieve data assuming that connection ‘cnCust’ is already exists.

Example
Dim RsCust as ADODB.Recordset
Set RsCust = New Recordset
Rscust.Open “Customer”, CnCust

Private Sub Class_GetDataMember(Datamember As String, Data As Object)
Set Data = RsCust
End Sub

Creating methods of the class
After creating properties for a class functionality to the class can be provided by adding methods to the class.  Public Sub and function procedures are used to create methods of the class.

Example (Method)
Public Function Name(ByVal Newstr As Str)
If IsNumeric (Newstr) = True OR Newstr = Empty Then
MsgBox “Enter a Valid Name”
End If
End Function

Creating Events for a class
Visual Basic have events for a class which notify the application of the occurrence of some action in the class.  Some important events are as:-

1)                  Initialize Event
Occurs when an instance of class is created.  It is triggered before any properties are set and is used to initialize any data that the class uses.  It can also be used to load any forms used by the class.

Syntax:
Private Sub Object_Initialize ( )

Following is the code in initialize event of the class that creates and opens connection and a Recordset.

Example
Private Sub Class_Initilize ( )
Set CnCust = New ADODB.Connection
CnCust.Open “Provider = Microsoft.Jet.OLEDB.3.51; Data Source = C:\Program Files\ Microsoft Visual Studio\VB98\NWind.MDB”
Set RsCust = New ADODB.Recordset
RsCust.Open “Customers” CnCust
End Sub

2)                  Terminate Event
Occurs when object is set to ‘Nothing’ or when last reference to the object goes out of scope.
Syntax:
Private Sub Object.Terminate ( )

Example
Private Sub Class_Terminate ( )
Unload Form1
End Sub

Custom events can also be created in Visual Basic by:-
à    Defining the Event.
à    Write Code to trigger the event.
Following is the code required to create and trigger custom event: CaseText.  We place label and command button on the form an add class module to the application.  To support CaseText Event we declare an object variable MyObject using with Events keyword.  In Load event of the Form an instance of object Variable MyObject is created.  When command button is clicked the check procedure of MyObject is called which raises Event CaseText.

Example
     Code Window of Class Module

Public Event CaseText (ByVal StrVal as String)
Public Sub Check ( )
RaiseEvent CaseText(“Raising an Event”)
End Sub

Code Window of Form Module

Public WithEvents MyObject As Class1
Private Sub Form_Load ( )
Set MyObject = New Class1
End Sub

Private Sub MyObject_CaseText (ByVal MStr As String)
Label1.Caption = MStr
End Sub

Private Sub Command1_Click ( )
Call MyObject.Check
End sub



Top

No comments:

Post a Comment