Module 3: Language and Syntax Enhancements
Module 3: Language and Syntax Enhancements
Syntax Enhancements
Contents
Overview 1
Data Types 2
Using Variables 9
Demonstration: Using Variables and
Data Structures 20
Functions, Subroutines, and Properties 21
Lab 3.1: Working with Variables and
Procedures 29
Exception Handling 36
Demonstration: Structured Exception
Handling 48
Lab 3.2: Implementing Structured
Exception Handling 49
Review 52
Information in this document, including URL and other Internet Web site references, is subject to
change without notice. Unless otherwise noted, the example companies, organizations, products,
domain names, e-mail addresses, logos, people, places and events depicted herein are fictitious,
and no association with any real company, organization, product, domain name, e-mail address,
logo, person, place or event is intended or should be inferred. Complying with all applicable
copyright laws is the responsibility of the user. Without limiting the rights under copyright, no part
of this document may be reproduced, stored in or introduced into a retrieval system, or transmitted
in any form or by any means (electronic, mechanical, photocopying, recording, or otherwise), or
for any purpose, without the express written permission of Microsoft Corporation.
Microsoft may have patents, patent applications, trademarks, copyrights, or other intellectual
property rights covering subject matter in this document. Except as expressly provided in any
written license agreement from Microsoft, the furnishing of this document does not give you any
license to these patents, trademarks, copyrights, or other intellectual property.
Microsoft, MS-DOS, Windows, Windows NT, ActiveX, BizTalk, FrontPage, IntelliSense, JScript,
Microsoft Press, Outlook, PowerPoint, Visio, Visual Basic, Visual C++, Visual C#, Visual
InterDev, Visual J#, Visual SourceSafe, Visual Studio, and Windows Media are either registered
trademarks or trademarks of Microsoft Corporation in the U.S.A. and/or other countries.
The names of actual companies and products mentioned herein may be the trademarks of their
respective owners.
Module 3: Language and Syntax Enhancements iii
Instructor Notes
Presentation: This module provides students with the knowledge needed to use many of the
90 Minutes new language and syntax enhancements to the Microsoft® Visual Basic®
language, including variable declaration and initialization, procedure syntax,
Labs: structured exception handling, and assignment operator changes.
75 Minutes
In the labs, students will create a simple application that uses variables and
procedures to add customers to a customer array. The students will then add
structured exception handling to the application.
After completing this module, students will be able to:
Describe the changes to data types in Visual Basic .NET.
Declare and initialize variables and arrays.
Use shorthand syntax to assign values to variables.
Implement functions and subroutines.
Call the default properties of an object.
Use the new Try…Catch…Finally statement to implement structured
exception handling.
Required Materials
To teach this module, you need the following materials:
Microsoft PowerPoint® file 2373B_03.ppt
Module 3, “Language and Syntax Enhancements”
Lab 3.1, Working with Variables and Procedures
Lab 3.2, Implementing Structured Exception Handling
Preparation Tasks
To prepare for this module, you should:
Read all of the materials for this module.
Read the instructor notes and the margin notes for the module.
Practice the demonstrations.
Complete the labs.
iv Module 3: Language and Syntax Enhancements
Demonstrations
This section provides demonstration procedures that will not fit in the margin
notes or are not appropriate for the student notes.
Module Strategy
Use the following strategy to present this module:
Data Types
This lesson shows some of the new data types and the changes to existing
data types. This lesson also introduces the common type system, the
differences between value and reference types, and the CType keyword that
is essential for converting variables of one data type to another. Creating
objects is not covered in this module, but it may be necessary to point out
some simple syntax in the examples in which the New keyword is used.
This topic will be covered in Module 4, “Object-Oriented Design for
Visual Basic .NET,” in Course 2373B, Programming with Microsoft
Visual Basic .NET.
It may be worth pointing out that the new Microsoft .NET Framework
classes provide alternative ways to perform many similar tasks that can be
performed in the Visual Basic language. The System.Collections
namespace contains several good examples of these classes.
Using Variables
This lesson shows how to declare and initialize variables in
Visual Basic .NET and introduces changes to variable scope. The topic of
data structures is introduced. This topic will be covered further in Module 5,
“Object-Oriented Programming in Visual Basic .NET,” in Course 2373B,
Programming with Microsoft Visual Basic .NET. Point out that Option
Explicit is the default compiler option in Visual Basic .NET. Finally,
introduce students to the new shorthand syntax for assignment operators.
Functions, Subroutines, and Properties
This lesson shows the changes to functions and subroutines, in addition to
the changes to the calling syntax for object properties. Remind students that
object property creation will be covered in Module 5, “Object-Oriented
Programming in Visual Basic .NET,” in Course 2373B, Programming with
Microsoft Visual Basic .NET.
In the default property examples that use ADO Recordset objects, focus the
discussion on the errors generated by incorrect use of default properties.
Other errors may also be generated by assigning incorrect data types to
other variables, but these errors should be ignored.
Exception Handling
This lesson shows the new structured exception handling syntax and
explains why it is preferable to unstructured exception handling. To create
exceptions by using the Throw statement, as used in the notes and labs,
requires a basic understanding of object constructors that is not covered
until Module 5, “Object-Oriented Programming in Visual Basic .NET,” in
Course 2373B, Programming with Microsoft Visual Basic .NET. Point this
out to students and provide a short explanation of this statement.
Module 3: Language and Syntax Enhancements 1
Overview
Topic Objective
To provide an overview of
the module topics and
objectives. Data Types
Lead-in Using Variables
In this module, you will learn
about the enhancements to Functions, Subroutines, and Properties
the Visual Basic language
and syntax in Exception Handling
Visual Basic .NET.
Data Types
Topic Objective
To explain the changes to
data types in
Visual Basic .NET. Common Type System
Lead-in Comparing Value-Type and Reference-Type Variables
This lesson discusses
changes to data types and New Data Types
how they are used in
Visual Basic .NET code. Changes to Existing Data Types
Using CType to Convert Data Types
Value-Type Variables
Value-type variables directly contain their data. Each value-type variable has its
own copy of data, so operations on one value-type variable cannot affect
another variable.
Examples of value-type variables include integers, doubles, floats, and
structures.
Reference-Type Variables
Reference-type variables contain references to their data. The data is stored in
an instance. Two reference-type variables can reference the same object, so
operations on one reference-type variable can affect the object referenced by
another reference-type variable.
Examples of reference-type variables include strings, arrays, and classes.
Module 3: Language and Syntax Enhancements 5
Integer
The Integer and Long data types in Visual Basic 6.0 have a different meaning
in Visual Basic .NET, as described in the following table.
Visual Basic 6.0 Visual Basic .NET .NET Framework
Integer size data type data type and runtime type
Variant
Visual Basic .NET updates the universal data type to Object for compatibility
with the common language runtime.
Currency
The Currency data type is not supported in Visual Basic .NET. You can use
the Decimal data type as a replacement. The Decimal data type uses 12 bytes of
memory, and allows more digits on both sides of the decimal point.
Date
The Date data type is available in Visual Basic .NET but is not stored in the
same format as it was in Visual Basic 6.0.
String
Fixed-length strings are no longer supported, but you can simulate this behavior
by padding a string to the desired length with spaces, as shown in the following
example:
'Create a string containing spaces
Dim s As String = Space(10)
The type name String is an alias for the System.String class. Therefore, String
and System.String can be used interchangeably. The String class represents a
string of characters that cannot be modified after the text has been created.
Methods that appear to modify a string value actually return a new instance of
the string containing the modification.
This can impact performance in applications performing a large number of
repeated modifications to a string, so the System.Text.StringBuilder object is
provided. This object allows you to modify a string without creating a new
object, and is therefore a better choice if you are performing a large number of
string manipulations. The following example shows how to create a
StringBuilder variable and how to append values to it:
Dim s As New System.Text.StringBuilder()
Delivery Tip s.Append("This")
Point out the StringBuilder
s.Append(" is")
class and the example
shown in the notes. s.Append(" my")
s.Append(" text!")
MsgBox(s.ToString) 'generates "This is my text!"
Visual Basic 6.0 provides many string manipulation methods that are still
available in Visual Basic .NET. The System.String class also has many
predefined properties and methods that simulate this behavior by using an
object-oriented approach. These properties and methods include Insert,
Length, Copy, Concat, Replace, Trim, ToLower, and ToUpper. For more
information, search for “string methods” in the Visual Studio .NET
documentation.
8 Module 3: Language and Syntax Enhancements
Syntax
Use the following syntax to convert data types:
CType(expression, typename)
expression
The expression argument can be any valid expression, such as a variable, a
result of a function, or a constant value.
typename
The typename argument can be any expression that is valid within an As
clause in a Dim statement, such as the name of any data type, object,
structure, class, or interface.
Example
The following examples show how to convert a String value to an Integer, and
how to convert to a data structure type:
Dim x As String, y As Integer
x = "34"
y = CType(x, Integer)
Using Variables
Topic Objective
To explain how to declare,
initialize, and use
variables and arrays in Declaring and Initializing Variables and Arrays
Visual Basic .NET.
Declaring Multiple Variables
Lead-in
This lesson explains the Variable Scope
differences between
declaring, initializing, and Creating Data Structures
using variables in
Visual Basic 6.0 and Compiler Options
Visual Basic .NET.
Assignment Operators
'Array
'Array declarations
declarations
Dim
Dim Month(12)
Month(12) AsAs Integer
Integer 'Creates
'Creates array
array with
with 13
13 elements
elements
'Initialize
'Initialize the
the array
array with
with 1212 elements
elements
Dim
Dim aMonth(
aMonth( )) As
As Integer
Integer == {1,2,3,4,5,6,7,8,9,10,11,12}
{1,2,3,4,5,6,7,8,9,10,11,12}
Examples
The following code shows how to declare and initialize variables in a single
statement:
Dim i As Integer = 21
Dim dToday As Date = Today( )
Dim dblFloat As Double = 1232.23312
Delivery Tip Dim dBirthday As Date = #1/1/1995#
Explain the examples on the
Dim iCalculate As Integer = i * 5
slide.
Module 3: Language and Syntax Enhancements 11
Redimensioning Arrays
In Visual Basic 6.0, you can only redimension an array if it is not dimensioned
when it is declared. In Visual Basic .NET, you can redimension an array if it is
dimensioned when it is declared.
Using the Preserve keyword will copy the original array into a new array,
which can result in inefficient code. If you need to do this often, consider using
the ArrayList class for a more efficient approach.
12 Module 3: Language and Syntax Enhancements
Variable Scope
Topic Objective
To explain the concept of Procedure scope
block scope and how it is
implemented in Variables accessible to entire procedure
Visual Basic .NET.
Lead-in Block scope
Visual Basic .NET Variables only accessible within that block
introduces a new level of
variable scope into the Lifetime of block variable is entire procedure
Visual Basic language:
block scope. Dim
Dim iLooper
iLooper As
As Integer
Integer 'Procedure
'Procedure level
level variable
variable
For
For iLooper
iLooper == 11 to
to 10
10
Dim
Dim iMax As Integer 'Block
iMax As Integer 'Block level
level variable
variable
iMax
iMax == iLooper
iLooper
Next
Next
MsgBox
MsgBox (iMax)
(iMax) 'This
'This line
line generates
generates aa compiler
compiler error
error
Example
Consider an example in which you need procedure scope for your variables.
Structure
Structure Customer
Customer
Public
Public CustID
CustID As
As Integer
Integer
Dim
Dim CustDayPhone As
CustDayPhone As String
String 'Defaults
'Defaults to
to public
public
Private
Private CustNightPhone
CustNightPhone As As String
String 'Private
'Private allowed
allowed
End Structure
End Structure
The syntax for using structures and classes in Visual Basic .NET is very
similar. In fact, structures support most features of classes, including methods.
Note For more information about data structures and access modifiers, see
Module 5, “Object-Oriented Programming in Visual Basic .NET,” in Course
2373B, Programming with Microsoft Visual Basic .NET.
16 Module 3: Language and Syntax Enhancements
Compiler Options
Topic Objective
To explain how setting
compiler options affects
data types. Option Explicit
Lead-in Default option
Setting various compiler
options can alter the way Option Strict
your data types behave.
Enforces strict type semantics and restricts implicit type
conversion
Late binding by means of the Object data type is not
allowed
Option Base 1 Not Supported
Arrays must start at zero
Option Strict
Option Strict is a new compiler option in Visual Basic .NET that controls
whether variable type conversions are implicit or explicit. This option prevents
the data inaccuracies that may result from implicit narrowing conversions.
If you select this option, implicit widening type conversion, such as converting
an Integer to a Long, is allowed. However, implicit narrowing type
conversions, such as converting a numeric String to an Integer, or a Long to
an Integer, cause a compiler error.
Module 3: Language and Syntax Enhancements 17
The following example shows a subroutine that takes an Integer argument but
is passed a String value, resulting in a compiler error:
Sub TestLong(ByRef lng As Long)
...
End Sub
TestLong("1234")
'Causes a compiler error because narrowing is unacceptable
Late binding is not allowed under Option Strict. This means that any variable
declared As Object can only use the methods provided by the Object class.
Any attempt to use methods or properties belonging to the data type stored in
the variable will result in a compiler error.
The following example shows what will happen if you use late binding when
Option Strict is enabled. A String value in an Object variable is allowed, but
calling a method from the String class is not allowed.
Dim x As Object
x = "MyStringData"
Option Base 1
In Visual Basic .NET, all arrays must start with a lower bound of 0. Therefore,
Option Base 0|1 is not a compiler option in Visual Basic .NET. This is
consistent with all programming languages using the .NET Framework.
18 Module 3: Language and Syntax Enhancements
Assignment Operators
Topic Objective
To explain the new
assignment operators.
Lead-in Simplified variable assignment operators
Visual Basic .NET supports
a simplified syntax for *= Multiplication
assignment operations. /= Division
+= Addition
-= Subtraction
&= String concatenation
Example: iResult += 25
iResult equals the existing value for iResult, plus 25
Syntax
The original syntax and the shorthand version are shown below:
Original: {variable} = {variable} {operator} {expression}
Shorthand: {variable} {operator} = {expression}
For example:
Original: iResult = iResult + 25
Shorthand: iResult += 25
Module 3: Language and Syntax Enhancements 19
Shorthand Operators
The following table shows how the compiler will interpret the new shorthand
operators.
Assignment
operator Purpose
Example
The following example shows how to use the new assignment operators to
concatenate character strings and provides the resulting string:
Dim myString As String = "First part of string; "
myString &= "Second part of string"
MsgBox (myString)
'Displays "First part of string; Second part of string"
20 Module 3: Language and Syntax Enhancements
Optional Arguments
Topic Objective
To explain changes in how
you use optional arguments.
Lead-in Visual Basic 6.0
There are some changes to You do not need to specify default values for optional
how you use optional
arguments in
parameters
Visual Basic .NET. You can use the IsMissing function
Visual Basic .NET
You must include default values for optional parameters
The IsMissing function is not supported
Function
Function Add(Value1
Add(Value1 AsAs Integer,
Integer, Value2
Value2 As
As Integer,
Integer,
Optional
Optional Value3
Value3 As
As Integer
Integer == 0)
0) As
As Integer
Integer
Note You can use overloaded functions to provide the same functionality as
optional arguments. For more information about overloading, see Module 5,
“Object-Oriented Programming in Visual Basic .NET,” in Course 2373B,
Programming with Microsoft Visual Basic .NET.
Module 3: Language and Syntax Enhancements 25
You can also use the Return statement to return the value. This avoids linking
the return of the function to the function name, allowing for easier renaming of
functions. The following example shows how to use the Return statement to
return the value:
Function GetData( ) As String
...
Return "My data"
End Function
Note The Return statement exits the function immediately and returns the
value to the calling procedure.
Module 3: Language and Syntax Enhancements 27
rs.Fields.Item(1).Value
rs.Fields.Item(1).Value == Lab1.Text
Lab1.Text 'Valid
'Valid
rs.Fields(1).Value
rs.Fields(1).Value == Lab1.Text
Lab1.Text 'Valid
'Valid
rs.Fields(1)
rs.Fields(1) == Lab1.Text
Lab1.Text 'Not
'Not valid
valid
Lab1
Lab1 == "Data
"Data Saved"
Saved" 'Not
'Not valid
valid
rs.Fields(1) = Lab1.Text
'Not valid because Value is not parameterized
Lab1 = "Data Saved"
'Not valid because Text is not parameterized
Module 3: Language and Syntax Enhancements 29
Prerequisites
Before working on this lab, you must be familiar with using variables, arrays,
and procedures.
Scenario
In this lab, you will create a simple Microsoft Windows® Forms application in
which you can enter customer information into an array and then retrieve it. The
application will consist of a single form that you use to input this information.
Solution Files
There are solution files associated with this lab. The solution files are in the
install folder\Labs\Lab031\Solution folder.
Exercise 1
Creating the Customer Form
In this exercise, you will create the customer entry form.
Exercise 2
Adding a Customer
In this exercise, you will write code to add a new customer to an array of
customers when the user clicks Add Customer.
Id Integer
FirstName String
LastName String
DateOfBirth Date
To add a customer
1. Create the btnAddCustomer_Click event handler.
2. In the btnAddCustomer_Click event handler, create a local variable named
cCustomer based on the information in the following table.
Variable name Data type
cCustomer Customer
3. Assign the upper bound limit of the aCustomers array to the Id member of
the cCustomer object.
4. Assign the Text properties of the text boxes to the corresponding members
of the cCustomer variable as defined in the following table.
Use the CDate function to convert the text property of txtDOB to the Date
data type for use by the cCustomer.DateOfBirth member.
cCustomer member Text box
FirstName txtFirstName
LastName txtLastName
DateOfBirth txtDOB
5. Using the UBound function for the array index, add the cCustomer variable
to the aCustomers array.
Module 3: Language and Syntax Enhancements 33
6. Use the ReDim Preserve syntax and the UBound function to increase the
size of the aCustomers array by one.
This creates one more array element than is required. However, this is
acceptable for this exercise.
Important When you use the UBound function to increase the size of the
array, you must add the integer value of 1 to the result of the UBound
function.
7. Use the MsgBox function to display a message box that confirms that the
customer has been added.
8. Clear the txtFirstName, txtLastName, and txtDOB text boxes.
9. Save the project.
Exercise 3
Retrieving a Customer
In this exercise, you will write code to retrieve a customer from an array when
the user clicks Retrieve.
iIndex Integer
aCustomer Customer
sInput String
sMessage String
2. Use the InputBox function to ask the user to enter a customer identification
number, and then store the response in the sInput variable.
3. Use an If statement and the IsNumeric function to test whether the entered
data is numeric.
4. If the data is numeric, call the RetrieveCustomer function, and then pass it
the value of the sInput variable converted to an integer.
5. Store the return value of the RetrieveCustomer function in the aCustomer
variable.
6. To create a message to be displayed to the user, concatenate the values of
each of the aCustomer elements into the sMessage variable, and then
display the string in a message box.
7. Save the project.
Module 3: Language and Syntax Enhancements 35
Exception Handling
Topic Objective
To explain the extensions to
exception handling in
Visual Basic. NET. Structured Exception Handling
Lead-in Try…Catch…Finally
Exception handling is an
important topic in any Using Try…Catch…Finally
application.
Visual Basic .NET The System.Exception Class
introduces a powerful new
form of handling: structured Filtering Exceptions
exception handling.
Throwing Exceptions
Try…Catch…Finally
Topic Objective
To explain the basics of the
Try…Catch…Finally ...
...
syntax. Try
Try
'' Include
Include code
code to
to be
be tried
tried here
here
Lead-in '' Can
Can use
use Exit
Exit Try
Try to
to exit
exit block
block and
and resume
resume after
after End
End Try
Try
So how do you use the
Try…Catch…Finally Catch
Catch
syntax? '' Define
Define exception
exception type
type and
and action
action to
to be
be taken
taken
'' Can
Can use
use series
series of
of statements
statements (multiple
(multiple error
error handling)
handling)
Finally
Finally
'' Optional
Optional block
block
'' Define
Define actions
actions that
that need
need to
to take
take place
place
End
End Try
Try
...
...
Try Block
Note the following as you examine this code:
The Try…End Try block surrounds an area of code that might contain an
error.
Code placed in this block is considered protected.
If an exception occurs, processing is transferred to the nested Catch blocks.
You can use the Exit Try keyword to instantly exit the Try…End Try
block. Execution will resume immediately after the End Try statement.
40 Module 3: Language and Syntax Enhancements
Catch Block
If an exception occurs in the Try block, execution will continue at the
beginning of the nested Catch block. The Catch block is a series of statements
beginning with the keyword Catch followed by an exception type and an action
to be taken. The following are some guidelines for using the Catch block:
You can choose to handle all exceptions in one Catch block. You can also
declare multiple Catch blocks to filter the exception and handle particular
errors, similar to how you might use Select Case in previous versions of
Visual Basic.
You can filter using the different exception classes defined by the .NET
Framework and runtime, or by using your own exception classes.
You can use a When statement to compare the exception to a particular
exception number.
If you use filtering for the exceptions but do not handle the actual exception
that occurred, the exception is automatically raised up to the calling
procedure (or to the user if no calling procedure exists). However, by using
a Catch filter with the Exception class, you will catch all of the other
exceptions that you have not included in your filters. This is the equivalent
of a Case Else statement in a Select Case structure.
Finally Block
The Finally block is optional. If you include this block, it is executed after the
Try block if no errors occurred, or after the appropriate Catch block has been
processed.
The Finally block is always executed.
In this block, you can define actions that need to take place regardless of
whether an exception occurs. This may include actions such as closing files
or releasing objects.
The Finally block is most often used to clean up operations when a method
fails.
Module 3: Language and Syntax Enhancements 41
Using Try…Catch…Finally
Topic Objective
To explain a simple example
of structured exception Sub
Sub TrySimpleException
TrySimpleException
handling. Dim
Dim i1,
i1, i2,
i2, iResult
iResult AsAs Decimal
Decimal
i1
i1 == 22
22
Lead-in i2
i2 == 00
Let’s look at a simple Try
Try
example of iResult
iResult == i1
i1 // i2
i2 '' Cause
Cause divide-by-zero
divide-by-zero error
error
Try…Catch…Finally MsgBox
MsgBox (iResult)
(iResult) '' Will
Will not
not execute
execute
syntax.
Catch
Catch eException
eException As
As Exception
Exception '' Catch
Catch the
the exception
exception
MsgBox
MsgBox (eException.Message)
(eException.Message) '' Show
Show message
message to
to user
user
Finally
Finally
Beep
Beep
End
End Try
Try
End
End Sub
Sub
Note Any variables declared in any of the three blocks are scoped as block-
level variables. They cannot be accessed from outside of the block.
Module 3: Language and Syntax Enhancements 43
Filtering Exceptions
Topic Objective Dim
Dim x,
x, y,
y, zz As
As Integer,
Integer, bSucceeded
bSucceeded AsAs Boolean
Boolean == True
True
To explain a more advanced Try
Try
example of Try...Catch... 'Perform
'Perform various
various operations
operations on
on variables
variables
Finally syntax that filters ...
...
exceptions. Catch
Catch eException
eException As As DivideByZeroException
DivideByZeroException
MsgBox("You
MsgBox("You havehave attempted
attempted to
to divide
divide by
by zero.")
zero.")
Lead-in bSucceeded
bSucceeded == False
False
Let’s look at a more Catch
Catch eException
eException As As OverflowException
OverflowException
advanced example of MsgBox("You
MsgBox("You havehave encountered
encountered an
an overflow.")
overflow.")
Try...Catch...Finally syntax bSucceeded
bSucceeded == False
False
that involves filtering. ...
...
Catch
Catch When
When Err.Number
Err.Number == 1111
MsgBox("Error
MsgBox("Error occurred.")
occurred.")
bSucceeded
bSucceeded == False
False
Finally
Finally
If
If bSucceeded
bSucceeded Then
Then
...
...
End
End If
If
End Try
End Try
Explain that
DivideByZeroException,
OverflowException, and
ConstraintException are
all examples of exception
classes that are based on
(inherit from) the
System.Exception class.
Example
The following example shows how to use filtering to handle several different
exceptions in one Try...Catch...Finally statement:
Sub TryComplexException( )
Dim x, y, z As Integer, bSucceeded As Boolean = True
Try
'Perform various operations on variables
...
Catch eException As DivideByZeroException
MsgBox("You have attempted to divide by zero!")
bSucceeded = False
Catch eException As OverflowException
MsgBox("You have encountered an overflow.")
bSucceeded = False
Catch eException As ConstraintException
MsgBox(eException.ToString)
bSucceeded = False
Catch When Err.Number = 11
MsgBox("Error occurred")
bSucceeded = False
Finally
If bSucceeded Then
MsgBox("Success!")
Else
MsgBox("Failure")
End If
End Try
End Sub
Throwing Exceptions
Topic Objective
To explain how to throw
your own exceptions.
Lead-in Use Throw keyword instead of Err.Raise
You can raise your own
exceptions by using the Try
Try
Throw statement. If
If xx == 00 Then
Then
Throw
Throw NewNew Exception("x
Exception("x equals
equals zero")
zero")
Else
Else
Throw
Throw NewNew Exception("x
Exception("x does
does not
not equal
equal zero")
zero")
End
End If
If
Catch
Catch eException
eException As As Exception
Exception
MsgBox("Error:
MsgBox("Error: " && eException.Message)
" eException.Message)
Finally
Finally
MsgBox("Executing
MsgBox("Executing finally
finally block")
block")
End
End Try
Try
End Try
This example will throw an exception if the value of the variable x is zero. The
Delivery Tip If statement creates a new Exception object and passes a string containing an
This is an example of using
object constructors for the
exception description to the object constructor. This means that the Catch block
Exception class. They will can handle the exception as it would deal with a normal system exception.
be covered in Module 4,
If a Throw statement is not executed within a Try block, the exception will be
“Object-Oriented Design for
Visual Basic .NET” and
raised to the calling procedure.
Module 5, “Object-Oriented
Programming in Note For more information about object constructors, see Module 5, “Object-
Visual Basic .NET,” in Oriented Programming in Visual Basic .NET,” in Course 2373B, Programming
Course 2373B, with Microsoft Visual Basic .NET.
Programming with Microsoft
Visual Basic .NET.
48 Module 3: Language and Syntax Enhancements
Prerequisites
Before working on this lab, you must:
Complete Lab 3.1.
Be familiar with using the Try…Catch…Finally statement for structured
exception handling.
Scenario
In this lab, you will add structured exception handling to the application that
you created in Lab 3.1.
Exercise 1
Adding Exception Handling to Customer Retrieval
In this exercise, you will add structured exception handling to the
RetrieveCustomer function that you created in Lab 3.1.
This throws a new exception that includes a specific message, while keeping
the original exception as an inner exception. The Try...Catch...Finally
block in the btnRetrieve_Click event handler catches this exception.
4. Delete the Finally block.
It serves no purpose in this procedure.
Review
Topic Objective
To reinforce module
objectives by reviewing key
points. Data Types
Lead-in Using Variables
The review questions cover
some of the key concepts Functions, Subroutines, and Properties
taught in the module.
Exception Handling
Statement (a) will fail because rs(0) returns a Field object; the Fields
collection is the default property of the Recordset object. This cannot be
assigned to the Text property of the txtData TextBox because the data
types are not compatible.
Statement (b) will fail because Value is the default property of the Field
object, and it does not take a parameter. This causes the compiler to
attempt to assign the Field object to the txtData.Text property,
resulting in an error.
Statement (c) will succeed because Item is the default property of the
Fields object, and it does take a parameter.