Home > Articles > Certification > Microsoft Certification

This chapter is from the book

Handling Exceptions

Implement error handling in the UI: Raise and handle errors.

Implement error handling in the UI: Create and implement custom error messages.

Abruptly terminating the program when an exception occurs is not a good idea. Your application should be able to handle the exception and (if possible) recover from it. If recovery is not possible you can take other steps, such as notifying the user and then gracefully terminating the application.

The .NET Framework allows exception handling to interoperate among languages and across machines. You can throw an exception in code written in VB .NET and catch it in code written in C#, for example. In fact, the .NET framework also allows you to handle common exceptions thrown by legacy COM applications and legacy nonCOM Win32 applications.

Exception handling is such an integral part of .NET framework that when you look up a method in the product documentation, a section will always specify what exceptions a call to that method might throw.

You can handle exceptions in Visual Basic .NET programs by using a combination of the exception handling statements: Try, Catch, Finally, and Throw. In this section of the chapter I'll show how to use these statements.

The Try Block

You should place the code that can cause exception in a Try block. A typical Try block will look like this:

Try
  ' Code that may cause an exception
End Try

You can place any valid Visual Basic .NET statements inside a Try block. That can include another Try block or a call to a method that places some of its statement inside a Try block. Thus at runtime you can have a hierarchy of Try blocks placed inside each other. When an exception occurs at any point, the CLR will search for the nearest Try block that encloses this code. The CLR will then pass control of the application to a matching Catch block (if any) and then to the Finally block associated with this Try block.

A Try block cannot exist on its own; it must be immediately followed by one or more Catch blocks or by a Finally block.

The Catch Block

You can have several Catch blocks immediately following a Try block. Each Catch block handles an exception of a particular type. When an exception occurs in a statement placed inside a Try block, the CLR looks for a matching Catch block capable of handling that type of exception. The formula that CLR uses to match the exception is simple. It will look for the first Catch block with either an exact match for the exception or for any of the exception's base classes. For example, a DivideByZeroException will match with any of these exceptions: DivideByZeroException, ArithmeticException, SystemException, and Exception (progressively more general classes from which DivideByZeroException is derived). In the case of multiple Catch blocks, only the first matching Catch block will be executed. All other Catch blocks will be ignored.

NOTE

Unhandled Exceptions If No Catch block matches a particular exception, that exception becomes an unhandled exception. The unhandled exception is propagated back to the code that called the current method. If the exception is not handled there, it will propagate further up the hierarchy of method calls. If the exception is not handled anywhere, it goes to the CLR for processing. The Common Language Runtime's default behavior is to terminate the program immediately.

When you write multiple Catch blocks, you must arrange them from specific exception types to more general exception types. For example, the Catch block for catching DivideByZeroException should always precede the Catch block for catching ArithmeticException because the DivideByZeroException derives from ArithmeticException and is therefore more specific. You'll get a compiler error if you do not follow this rule.

A Try block need not necessarily have a Catch block associated with it, but in that case it must have a Finally block associated with it. Step by Step 3.2 demonstrates the use of multiple Catch blocks to keep a program running gracefully despite errors.

STEP BY STEP 3.2 Handling Exceptions

  1. Add a new Windows Form to your Visual Basic .NET project.

  2. Create a form similar to the one in Step By Step 3.1 with the same names for controls (see Figure 3.1).

  3. Add the following code to the Click event handler of btnCalculate:

    Private Sub btnCalculate_Click( _
     ByVal sender As System.Object, _
     ByVal e As System.EventArgs) Handles btnCalculate.Click
      ' put all the code that may require graceful 
      ' error recovery in a try block
      Try
        Dim decMiles As Decimal = _
         Convert.ToDecimal(txtMiles.Text)
        Dim decGallons As Decimal = _
         Convert.ToDecimal(txtGallons.Text)
        Dim decEfficiency As Decimal = decMiles /     decGallons
        txtEfficiency.Text = _
         String.Format("{0:n}", decEfficiency)
        ' each try block should at least 
        ' have one catch or finally block
        ' catch blocks should be in order 
        ' of specific to the generalized 
        ' exceptions otherwise compilation 
        ' generates an error
      Catch fe As FormatException
        Dim msg As String = String.Format( _
         "Message: {0}\n Stack Trace:\n {1}", _
         fe.Message, fe.StackTrace)
        MessageBox.Show(msg, fe.GetType().ToString())
      Catch dbze As DivideByZeroException
        Dim msg As String = String.Format( _
         "Message: {0}\n Stack Trace:\n {1}", _
         dbze.Message, dbze.StackTrace)
        MessageBox.Show(msg, dbze.GetType().ToString())
        ' catches all CLS-compliant exceptions
      Catch ex As Exception
        Dim msg As String = String.Format( _
         "Message: {0}\n Stack Trace:\n {1}", _
         ex.Message, ex.StackTrace)
        MessageBox.Show(msg, ex.GetType().ToString())
        ' catches all other exception including 
        ' non-CLS-compliant exceptions
      Catch
        ' just rethrow the exception to the caller
        Throw
      End Try

    End Sub

  4. Set the form as the startup object for the project.

  5. Run the project. Enter values for miles and gallons and click the Calculate button to calculate the mileage efficiency as expected. Now enter the value zero in the gallons control and run the program. You will see that instead of abruptly terminating the program (as in the earlier example), the program shows a message about a DivideByZeroException (see Figure 3.4). After you dismiss the message, the program will continue running. Now enter some alphabetic characters in the fields instead of numbers and hit the calculate button again. This time you'll get a FormatException message and the program will continue to run. Now try entering a very large value for both the fields. If the values are large enough, the program will encounter an OverflowException, but since the program is catching all types of exceptions it will continue running.

Figure 3.4 DivideByZeroException.

The program in Step By Step 3.2 displays a message box when an exception occurs. The StackTrace property lists the methods that led up to the exception in the reverse order of their calling sequence to help you understand the flow of logic of the program. In a real application, you might choose to try to automatically fix the exceptions as well.

TIP

CLS- and Non-CLS–Compliant Exceptions All languages that follow the Common Language Specification (CLS) throw exceptions whose type is or derives from System.Exception. A non-CLS–compliant language might throw exceptions of other types as well. You can catch those types of exceptions by placing a general Catch block (one that does not specify any exception) within a Try block. In fact, a general Catch block can catch exceptions of all types, so it is most generic of all Catch blocks. This means that it should be the last Catch block among the multiple Catch blocks associated with a Try block.

When you write a Catch block to catch exceptions of the general Exception type, it will catch all CLS-compliant exceptions. That includes all exceptions unless you're interacting with legacy COM or Win32 API code. If you want to catch all exceptions, CLS-compliant or not, you can use a Catch block with no specific type. This Catch block must be last in the list of Catch blocks because it is the most generic.

If you are thinking that it's a good idea to catch all sorts of exceptions in your code and suppress them as soon as possible, think again. A good programmer will only catch an exception in code if the answer is yes to one or more of these questions:

  • Will I attempt to recover from this error in the Catch block?

  • Will I log the exception information in system event log or any other log file?

  • Will I add relevant information to the exception and rethrow it?

  • Will I execute cleanup code that must run even if an exception occurs?

If you answered no to all those questions, you should not catch the exception but rather just let it go. In that case, the exception will propagate up to the code that is calling your code. Possibly that code will have a better idea of what to do with the exception.

The Throw Statement

A Throw statement explicitly generates an exception in your code. You can use Throw to handle execution paths that lead to undesired results.

You should not throw an exception for anticipated cases, such as the user entering an invalid username or password. This occurrence can be handled in a method that returns a value indicating whether the logon was successful. If you don't have enough permissions to read records from the user table, that's a better candidate to raise an exception because a method to validate users should normally have read access to the user table.

Using exceptions to control the normal flow of execution is bad for two reasons:

  1. It can make your code difficult to read and maintain because using Try and Catch blocks to deal with exceptions forces you to separate the regular program logic between separate locations.

  2. It can make your programs slower because exception handling consumes more resources than just returning values from a method.

You can use the Throw statement in two ways. In its simplest form, you can just rethrow an exception that you've caught in a Catch block:

Catch ex As Exception
  ' TODO: Add code to write to the event log
  Throw

This usage of the Throw statement rethrows the exception that was just caught. It can be useful when you don't want to handle the exception yourself but want to take other actions (such as recording the error in an event log or sending an email notification about the error) when the exception occurs. Then you can pass the exception unchanged to the next method in the calling chain.

TIP

Custom Error Messages When creating an exception class, you should use the constructor that allows you to associate a custom error message with the exception instead of using the default constructor. The custom error message can pass specific information about the cause of the error and a possible way to resolve it.

The second way to use a Throw statement is to throw explicitly created exceptions. For example, this code creates and throws an exception:

Dim strMessage As String = _
 "EndDate should be greater than the StartDate"
Dim exNew As ArgumentOutOfRangeException = _
 New ArgumentOutOfRangeException(strMessage)
Throw exNew

In this example I first created a new instance of the Exception object and associated a custom error message with it Then I threw the newly created exception.

You are not required to put this usage of the Throw statement inside a Catch block because you're just creating and throwing a new exception rather than rethrowing an existing one. You will typically use this technique in raising your own custom exceptions. I'll show how to do that later in this chapter.

An alternate way to throw an exception is to throw it after wrapping it with additional useful information, for example:

Catch ane As ArgumentNullException
  ' TODO: Add code to create an entry in the log file
  Dim strMessage As String = "CustomerID cannot be null"
  Dim aneNew As ArgumentNullException = _
   New ArgumentNullException(strMessage)
  Throw aneNew

You might need to catch an exception that you cannot handle completely. You would then perform any required processing and throw a more relevant and informative exception to the calling code, so that it can perform the rest of the processing. In this case, you can create a new exception whose constructor wraps the previously caught exception in the new exception's InnerException property. The calling code will now have more information available to handle the exception appropriately.

Because InnerException is also an exception, it might also store an exception object in its InnerException property, so what you are propagating is a chain of exceptions. This information can be very valuable at debugging time because it allows you to trace the problem to its origin.

The Finally Block

The Finally block contains the code that always executes whether any exception occurred. You can use the Finally block to write cleanup code to maintain your application in a consistent state and preserve the external environment. As an example you can write code to close files, database connections, or related I/O resources in a Finally block.

TIP

No Code in Between Try, Catch, and Finally Blocks When you write Try, Catch, and Finally blocks, they must be in immediate succession. You cannot write any code between the blocks, although you can place comments between them.

It is not necessary for a Try block to have an associated Finally block. However, if you do write a Finally block, you cannot have more than one, and the Finally block must appear after all the Catch blocks.

Step By Step 3.3 illustrates the use of the Finally block.

STEP BY STEP 3.3 Using a Finally Block

  1. Add a new Windows Form to your Visual Basic .NET project.

  2. Place two TextBox controls (txtFileName and txtText), two Label controls, and a Button control (btnSave) on the form's surface and arrange them as shown in Figure 3.5.

Figure 3.5 An application to test a Finally block.

  1. Double-click the Button control to open the form's module. Enter a reference at the top of the module:

    Imports System.IO
  2. Enter this code to handle the Button's Click event:

    Private Sub btnSave_Click(ByVal sender As System.Object, _
     ByVal e As System.EventArgs) Handles btnSave.Click
      ' A StreamWriter writes characters to a stream 
      Dim sw As StreamWriter
      Try
        sw = New StreamWriter(txtFilename.Text)
        ' Attempt to write the textbox contents in a file
        Dim strLine As String
        For Each strLine In txtText.Lines
          sw.WriteLine(strLine)
        Next
        ' This line only executes if 
        ' there were no exceptions so far
        MessageBox.Show( _
         "Contents written, without any exceptions")
        ' Catches all CLS-complaint exceptions
      Catch ex As Exception
        Dim msg As String = String.Format( _
       "Message: {0}\n Stack Trace:\n {1}", _
       ex.Message, ex.StackTrace)
        MessageBox.Show(msg, ex.GetType().ToString())
        GoTo endit
        ' The finally block is always 
        ' executed to make sure that the 
        ' resources get closed whether or 
        ' not an exception occurs. 
        ' Even if there is a goto statement 
        ' in catch or try block the
        ' final block is first executed before 
        ' the control goes to the label
      Finally
        If Not sw Is Nothing Then
          sw.Close()
        End If
        MessageBox.Show( _
         "Finally block always executes " & _
         "whether or not exception occurs")
      End Try
    EndIt:
      MessageBox.Show("Control is at label: end")

    End Sub

  3. Set the form as the startup object for the project.

  4. Run the project. Enter a file name and some text. Watch the order of the messages and note that the message box from the Finally block will always be displayed prior to the message box from the end label.

TIP

Finally Block Always Executes If you have a Finally block associated with a Try block, the code in the Finally block will always execute, regardless of whether an exception occurs.

Step By Step 3.3 illustrates that the Finally block always executes, even if a transfer of control statement, such as GoTo, is within a Try or Catch block. The compiler will not allow a transfer of control statement within a Finally block.

NOTE

Throwing Exceptions from a Finally Block Although throwing exceptions from a Finally block is perfectly legitimate, you should avoid doing so. A Finally block there might already have an unhandled exception waiting to be handled.

The Finally statement can be used in a Try block with no Catch block. For example:

Try
  ' Write code to allocate some resources
Finally
  ' Write code to Dispose all allocated resources
End Try

This usage ensures that allocated resources are properly disposed of no matter what happens in the Try block.

  • An exception occurs when a program encounters any unexpected problem during normal execution.

  • The Framework Class Library (FCL) provides two main types of exceptions: SystemException and ApplicationException. A SystemException represents an exception thrown by the Common Language Runtime while an ApplicationException represents an exception thrown by the your own code.

  • The System.Exception class is the base class for all CLS-compliant exceptions and provides the common functionality for exception handling.

  • A Try block consists of code that might raise an exception. A Try block cannot exist on its own but should be immediately followed by one or more Catch blocks or a Finally block.

  • The Catch block handles any exception raised by the code in the Try block. The runtime looks for a matching Catch block to handle the exception and uses the first Catch block with either the exact same exception or any of the exception's base classes.

  • If multiple Catch blocks are associated with a Try block, then the Catch blocks should be arranged in order from specific to general exception types.

  • The Throw statement is used to raise an exception.

  • The Finally block is used to enclose any code that needs to be run irrespective of whether an exception is raised.

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