Mastering the Visual Basic Language: Procedures, Error Handling, Classes, and Objects
- Sub Procedures
- Creating Functions
- Using Optional Arguments
- Passing a Variable Number of Arguments
- Preserving Data Between Procedure Calls
- Understanding Scope
- Handling Runtime Errors
- Unstructured Exception Handling
- Structured Exception Handling
- Introducing Classes and Objects
- Summary
- Q&A
- Workshop
Today, we're going to look at some crucial aspects of the Visual Basic language: procedures such as Sub procedures and functions, procedure scope, and exception (runtime error) handling. We'll also get an introduction to a topic that's become central to Visual Basic: classes and objects.
Now that our code is growing larger, it's good to know about procedures, which allow us to break up our code into manageable chunks. In fact, in Visual Basic, all executable code must be in procedures. There are two types of procedures: Sub procedures and functions. In Visual Basic, Sub procedures do not return values when they terminate, but functions do.
If you declare variables in your new procedures, those variables might not be accessible from outside the procedure, and that fact is new also. The area of your program in which a data item is visible and can be accessed in code is called scope, and we'll try to understand scopea crucial aspect of object-oriented programmingin this chapter.
We'll also look at handling runtime errors today. In Visual Basic, a runtime error is the same as an exception (that's not true in all languages), so we're going to look at exception handling. We'll see that there are two ways of heading off errors that happen at runtime before they become problems.
Finally, we'll get an introduction to classes and objects in this chapter. Visual Basic .NET programming is object-oriented programming (OOP), a fact you need to understand in depth to be a Visual Basic programmer. Today, we'll start by discussing classes and objects in preparation for our later work (such as Day 9, "Object-Oriented Programming," which is all about OOP). Here's an overview of today's topics:
Creating Sub procedures and functions
Passing arguments to procedures
Returning data from functions
Preserving data values between procedure calls
Understanding scope
Using unstructured exception handling
Using structured exception handling with Try/Catch
Using exception filtering in Catch blocks
Using multiple Catch statements
Throwing an exception
Throwing a custom exception
Understanding classes and objects
Supporting properties and methods in objects
All these topics are powerful ones, and they're all related. And today, the best place to start is with Sub procedures.
Sub Procedures
Procedures give you a way to break up your Visual Basic code, which is invaluable as that code grows longer and longer. Ideally, each procedure should handle one discrete task. That way, you break up your code by task; having one task per procedure makes it easier to keep in mind what each procedure does.
You can place a set of Visual Basic statements in a procedure, and when that procedure is called, those statements will be run. You can pass data to procedures for that code to work on and read that data in your code. The two types of procedures in Visual Basic are Sub procedures and functions, and both can read the data you pass them (the name Sub procedure comes from the programming term subroutine). However, only one type, functions, can also return data.
In fact, we've been creating Sub procedures in our code already (not surprisingly, because all Visual Basic code has to be in a procedure). All the code we developed yesterday went into the Sub procedure named Main, created with the keyword Sub:
Module Module1 Sub Main() Console.WriteLine("Hello there!") Console.WriteLine("Press Enter to continue...") Console.ReadLine() End Sub End Module
This Main Sub procedure is special because when a console application starts, Visual Basic calls Main automatically to start the program. When Main is called, the code is run as we wanted.
You can also create your own Sub procedures, giving them your own names. Those names should give an indication of the procedure's task. For example, to show the "Hi there!" message, you might create a new Sub procedure named ShowMessage by simply typing this text into the code designer:
Module Module1 Sub Main() End Sub Sub ShowMessage() End Sub End Module
In the ShowMessage Sub procedure, you place the code you want to execute, like this code to display the message:
Module Module1 Sub Main() End Sub Sub ShowMessage() Console.WriteLine("Hi there!") End Sub End Module
How do you make the code in the ShowMessage Sub procedure run? You can do that by calling it; to do so, just insert its name, followed by parentheses, into your code:
Module Module1 Sub Main() ShowMessage() Console.WriteLine("Press Enter to continue...") Console.ReadLine() End Sub Sub ShowMessage() Console.WriteLine("Hi there!") End Sub End Module
And that's it! Now when you run this code, Visual Basic will call the Main Sub procedure, which in turn will call the ShowMessage Sub procedure, giving you the same result as before:
Hi there! Press Enter to continue...
TIP
If you want to, you can use a Visual Basic Call statement to call a Sub procedure like this: Call ShowMessage(). This usage is still supported, although it goes back to the earliest days of Visual Basic, and there's no real reason to use it here.
Note the parentheses at the end of the call to ShowMessage like this: ShowMessage(). You use those parentheses to pass data to a procedure, and we'll take a look at that task next.
Passing Data to Procedures
Say you want to pass the message text you want to display to the ShowMessage Sub procedure, allowing you to display whatever message you want. You can do that by passing a text string to ShowMessage, like this:
Module Module1 Sub Main() ShowMessage("Hi there!") Console.WriteLine("Press Enter to continue...") Console.ReadLine() End Sub Sub ShowMessage() End Sub End Module
A data item you pass to a procedure in parentheses this way is called an argument. Now in ShowMessage, you must declare the type of the argument passed to this procedure in the procedure's argument list:
Module Module1 Sub Main() ShowMessage("Hi there!") Console.WriteLine("Press Enter to continue...") Console.ReadLine() End Sub Sub ShowMessage(ByVal Text As String) End Sub End Module
This creates a new string variable, Text, which you'll be able to access in the procedure's code. The ByVal keyword here indicates that the data is being passed by value, which is the default in Visual Basic (you don't even have to type ByVal, just Text As String here, and Visual Basic will add ByVal automatically).
Passing data by value means a copy of the data will be passed to the procedure. The other way of passing data is by reference, where you use the ByRef keyword. Passing by reference (which was the default in VB6) meant that the location of the data in memory will be passed to the procedure. Here's an important point to know: Because objects can become very large in Visual Basic, making a copy of an object and passing that copy can be very wasteful of memory, so objects are automatically passed by reference. We'll discuss passing by value and passing by reference in more detail in a page or two.
Visual Basic automatically fills the Text variable you declared in the argument list in this example with the string data passed to the procedure. This means you can access that data as you would the data in any other variable, as you see in the SubProcedures project in the code for this book, as shown in Listing 3.1.
Listing 3.1 Passing Data to a Sub Procedure (SubProcedures project, Module1.vb)
Module Module1 Sub Main() ShowMessage("Hi there!") Console.WriteLine("Press Enter to continue...") Console.ReadLine() End Sub Sub ShowMessage(ByVal Text As String) Console.WriteLine(Text) End Sub End Module
And that's all you need! Now you're passing data to Sub procedures and retrieving that data in the procedure's code. You can pass more than one argument to procedures as long as you declare each argument in the procedure's argument list. For example, say you want to pass the string to show and the number of times to show it to ShowMessage; that code might look like this:
Module Module1 Sub Main() ShowMessage("Hi there!", 3) Console.WriteLine("Press Enter to continue...") Console.ReadLine() End Sub Sub ShowMessage(ByVal Text As String, ByVal Times As Integer) For intLoopIndex As Integer = 1 To Times Console.WriteLine(Text) Next intLoopIndex End Sub End Module
Here's the result of this code:
Hi there! Hi there! Hi there! Press Enter to continue...
If you pass arguments by reference, using the ByRef keyword, Visual Basic passes the memory location of the passed data to the procedure (which gives the code in that procedure access to that data). You can read that data just as you do when you pass arguments by value:
Sub ShowMessage(ByRef Text As String, ByRef Times As Integer) For intLoopIndex As Integer = 1 To Times Console.WriteLine(Text) Next intLoopIndex End Sub
The code in the procedure has access to the data's location in memory, however, and that's something to keep in mind. So far, we've passed two literals ("Hello there!" and 3) to ShowMessage, and literals don't correspond to memory locations. But see what happens if you pass a variable by reference, like this:
Dim NumberOfTimes As Integer = 3 ShowMessage("Hi there!", NumberOfTimes) . . . Sub ShowMessage(ByRef Text As String, ByRef Times As Integer) For intLoopIndex As Integer = 1 To Times Console.WriteLine(Text) Next intLoopIndex End Sub
The code in the procedure has access to that variable, and if you change the value of the passed argument, you'll also change the value in the original variable:
Dim NumberOfTimes As Integer = 3 ShowMessage("Hi there!", NumberOfTimes) . . . Sub ShowMessage(ByRef Text As String, ByRef Times As Integer) For intLoopIndex As Integer = 1 To Times Console.WriteLine(Text) Next intLoopIndex Times = 24 End Sub
After this code is finished executing, for example, the variable NumberOfTimes will be left holding 24. This side effect is not unintentional; it's intentional. Being able to change the value of arguments is a primary reason to pass arguments by reference.
Changing the value of arguments passed by reference is one way to pass data from a procedure back to the calling code, but it can be troublesome. You can easily change an argument's value unintentionally, for example. A more structured way of passing data back from procedures is to use functions, which is the next topic.
You should also know that an Exit Sub statement, if you use one, causes an immediate exit from a Sub procedure in case you want to leave before executing all code. For example, say you have a Sub procedure that displays reciprocals of numbers you pass to it, but you want to avoid trying to find the reciprocal of 0. You could display an error message and exit the procedure like this if 0 is passed to the procedure:
Sub Reciprocal(ByVal dblNumber As Double) If dblNumber = 0 Then Console.WriteLine("Cannot find the reciprocal of 0.") Console.WriteLine("Press Enter to continue...") Console.ReadLine() Exit Sub End If Console.WriteLine("The reciprocal is " & 1 / dblNumber) Console.WriteLine("Press Enter to continue...") Console.ReadLine() End Sub
Sub Procedure Syntax
Like other Visual Basic statements, Sub procedures require a formal declaration. You declare Sub procedures with the Sub statement:
[ <attrlist> ] [{ Overloads | Overrides | Overridable | NotOverridable | MustOverride | Shadows | Shared }] [{ Public | Protected | Friend | Protected Friend | Private }] Sub name [(arglist)] [ Implements interface.definedname ] [ statements ] [ Exit Sub ] [ statements ] End Sub
And like other Visual Basic statements, many of the keywords here won't make sense at this point, so you can treat this information as reference material to come back to later. (Many of the keywords here deal with OOP, but we can't cover OOP in the detail needed here before knowing how to work with procedures, so it's impossible to avoid slightly circular definitions.) The parts of this statement are as follows:
attrlistThis is an advanced (and optional) topic; this is a list of attributes for use with this procedure. Attributes can add more information about the procedure, such as copyright data and so on. You separate multiple attributes with commas.
OverloadsSpecifies that this Sub procedure overloads one (or more) procedures defined with the same name in a base class. An overloaded procedure has multiple versions, each with a different argument list, as we'll see in Day 9. The argument list must be different from the argument list of every procedure that is to be overloaded. You cannot specify both Overloads and Shadows in the same procedure declaration.
OverridesSpecifies that this Sub procedure overrides (replaces) a procedure with the same name in a base class. The number and data types of the arguments must match those of the procedure in the base class.
OverridableSpecifies that this Sub procedure can be overridden by a procedure with the same name in a derived class.
NotOverridableSpecifies that this Sub procedure may not be overridden in a derived class.
MustOverrideSpecifies that this Sub procedure is not implemented. This procedure must be implemented in a derived class.
ShadowsMakes this Sub procedure a shadow of an identically named programming element in a base class. You can use Shadows only at module, namespace, or file level (but not inside a procedure). You cannot specify both Overloads and Shadows in the same procedure declaration.
SharedSpecifies that this Sub procedure is a shared procedure. As a shared procedure, it is not associated with a specific object, and you can call it using the class or structure name.
PublicProcedures declared Public have public access. There are no restrictions on the accessibility of public procedures.
ProtectedProcedures declared Protected have protected access. They are accessible only from within their own class or from a derived class. You can specify Protected access only for members of classes.
FriendProcedures declared Friend have friend access. They are accessible from within the program that contains their declaration and from anywhere else in the same assembly.
Protected FriendProcedures declared Protected Friend have both protected and friend accessibility. They can be used by code in the same assembly, as well as by code in derived classes.
PrivateProcedures declared Private have private access. They are accessible only within the element in which they're declared.
nameSpecifies the name of the Sub procedure.
arglistLists expressions representing arguments that are passed to the Sub procedure when it is called. You separate multiple arguments with commas.
Implements interface.definednameIndicates that this Sub procedure implements an interface. We'll see interfaces, which allow you to derive one class from several others, in Day 9.
statementsSpecifies the block of statements to be executed within the Sub procedure.
In addition, each argument in the argument list, arglist, has this syntax:
[ <attrlist> ] [ Optional ] [{ ByVal | ByRef }] [ ParamArray ] argname[( )] [ As argtype ] [ = defaultvalue ]
Here are the parts of arglist:
attrlistLists (optional) attributes that apply to this argument. Multiple attributes are separated by commas.
OptionalSpecifies that this argument is not required when the procedure is called. If you use this keyword, all following arguments in arglist must also be optional and be declared using the Optional keyword. Every optional argument declaration must supply a defaultvalue. Optional cannot be used for any argument if you also use ParamArray.
ByValSpecifies passing by value. ByVal is the default in Visual Basic.
ByRefSpecifies passing by reference, which means the procedure code can modify the value of the original variable in the calling code.
ParamArrayActs as the last argument in arglist to indicate that the final argument is an optional array of elements of the specified type. The ParamArray keyword allows you to pass an arbitrary number of arguments to the procedure. ParamArray arguments are always passed by value.
argnameSpecifies the name of the variable representing the argument.
argtypeSpecifies the data type of the argument passed to the procedure; this part is optional unless Option Strict is set to On. It can be Boolean, Byte, Char, Date, Decimal, Double, Integer, Long, Object, Short, Single, or String, or the name of an enumeration, structure, class, or interface.
defaultvalueSpecifies the default value for an optional argument, required for all optional arguments. It can be any constant or constant expression that evaluates to the data type of the argument. Note that if the type is Object, or a class, interface, array, or structure, the default value must be Nothing.
That gives us what we need to know about Sub procedures, we'll move on to functions next.