Home > Articles

Mastering the Visual Basic Language: Procedures, Error Handling, Classes, and Objects

This chapter is from the book

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 scope—a crucial aspect of object-oriented programming—in 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:

  • attrlist—This 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.

  • Overloads—Specifies 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.

  • Overrides—Specifies 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.

  • Overridable—Specifies that this Sub procedure can be overridden by a procedure with the same name in a derived class.

  • NotOverridable—Specifies that this Sub procedure may not be overridden in a derived class.

  • MustOverride—Specifies that this Sub procedure is not implemented. This procedure must be implemented in a derived class.

  • Shadows—Makes 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.

  • Shared—Specifies 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.

  • Public—Procedures declared Public have public access. There are no restrictions on the accessibility of public procedures.

  • Protected—Procedures 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.

  • Friend—Procedures 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 Friend—Procedures 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.

  • Private—Procedures declared Private have private access. They are accessible only within the element in which they're declared.

  • name—Specifies the name of the Sub procedure.

  • arglist—Lists expressions representing arguments that are passed to the Sub procedure when it is called. You separate multiple arguments with commas.

  • Implements interface.definedname—Indicates that this Sub procedure implements an interface. We'll see interfaces, which allow you to derive one class from several others, in Day 9.

  • statements—Specifies 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:

  • attrlist—Lists (optional) attributes that apply to this argument. Multiple attributes are separated by commas.

  • Optional—Specifies 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.

  • ByVal—Specifies passing by value. ByVal is the default in Visual Basic.

  • ByRef—Specifies passing by reference, which means the procedure code can modify the value of the original variable in the calling code.

  • ParamArray—Acts 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.

  • argname—Specifies the name of the variable representing the argument.

  • argtype—Specifies 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.

  • defaultvalue—Specifies 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.

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020