Home > Articles > Certification > Microsoft Certification

This chapter is from the book

Handling Exceptions

Implement error handling in the user interface:

  • Create and implement custom error messages.

  • Raise and handle errors.

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

TIP

Floating-Point Types and Exceptions Operations that involve floating-point types never produce exceptions. Instead, in exceptional situations, floating-point operations are evaluated by using the following rules:

If the result of a floating-point operation is too small for the destination format, the result of the operation becomes positive zero or negative zero.

If the result of a floating-point operation is too large for the destination format, the result of the operation becomes positive infinity or negative infinity.

If a floating-point operation is invalid, the result of the operation becomes NaN (not a number).

The .NET Framework allows exception handling to interoperate among languages and across machines. You can catch exceptions thrown by code written in one .NET language in a different .NET language. The .NET framework also allows you to handle exceptions thrown by legacy Component Object Model (COM) applications and legacy non-COM Windows applications.

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

You can handle exceptions in Visual C# .NET programs by using a combination of exception handling statements: try, catch, finally, and throw.

The try Block

You should place the code that might cause exceptions in a try block. A typical try block looks like this:

try
{
  //code that may cause exception
}

You can place any valid C# statements inside a try block, including another try block or a call to a method that places some of its statements inside a try block. The point is, at runtime you may have a hierarchy of try blocks placed inside each other. When an exception occurs at any point, rather than executing any further lines of code, the CLR searches for the nearest try block that encloses this code. The control is then passed 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 either one or more catch blocks or 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 the try block, the CLR looks for a matching catch block that is capable of handling that type of exception. A typical try-catch block looks like this:

try
{
  //code that may cause exception
}
catch(ExceptionTypeA)
{
  //Statements to handle errors occurring
  //in the associated try block
}
catch(ExceptionTypeB)
{
  //Statements to handle errors occurring
  //in the associated try block
}

The formula the CLR uses to match the exception is simple: While matching it looks for the first catch block with either the exact same exception or any of the exception's base classes. For example, a DivideByZeroException exception would match any of these exceptions: DivideByZeroException, ArithmeticException, SystemException, and Exception. In the case of multiple catch blocks, only the first matching catch block is executed. All other catch blocks are ignored.

When you write multiple catch blocks, you need to arrange them from specific exception types to more general exception types. For example, the catch block for catching a DivideByZeroException exception should always precede the catch block for catching a ArithmeticException exception. This is because the DivideByZeroException exception derives from ArithmeticException and is therefore more specific than the latter. The compiler flags an error if you do not follow this rule.

NOTE

Exception Handling Hierarchy If there is no matching catch block, an unhandled exception results. The unhandled exception is propagated back to its caller code. If the exception is not handled there, it propagates further up the hierarchy of method calls. If the exception is not handled anywhere, it goes to the CLR, whose default behavior is to terminate the program immediately.

A try block need not necessarily have a catch block associated with it, but if it does not, it must have a finally block associated with it.

STEP BY STEP 3.2 - Handling Exceptions

  1. Add a new Windows form to the project. Name it StepByStep3_2.

  2. Create a form similar to the one created in Step by Step 3.1 (refer to Figure 3.1), with the same names for the controls.

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

    private void btnCalculate_Click(
      object sender, System.EventArgs e)
    {
      //put all the code that may require graceful
      //error recovery in a try block
      try
      {
        decimal decMiles =
          Convert.ToDecimal(txtMiles.Text);
        decimal decGallons =
          Convert.ToDecimal(txtGallons.Text);
        decimal decEfficiency = decMiles/decGallons;
        txtEfficiency.Text =
          String.Format("{0:n}", decEfficiency);
      }
      // try block should at least have one catch or a
      // finally block. catch block should be in order
      // of specific to the generalized exceptions
      // otherwise compilation generates an error
      catch (FormatException fe)
      {
        string msg = String.Format(
           "Message: {0}\n Stack Trace:\n {1}",
           fe.Message, fe.StackTrace);
        MessageBox.Show(msg, fe.GetType().ToString());
      }
      catch (DivideByZeroException dbze)
      {
        string msg = 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(Exception ex)
      {
        string msg = String.Format(
          "Message: {0}\n Stack Trace:\n {1}",
          ex.Message, ex.StackTrace);
        MessageBox.Show(msg, ex.GetType().ToString());
      }
      //catches all other exceptions including
      //the NON-CLS compliant exceptions
      catch
      {
        //just rethrow the exception to the caller
        throw;
      }

    }

TIP

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

  1. Insert the Main() method to launch the form. Set the form as the startup object for the project.

  2. Run the project. Enter values for miles and gallons and click the Calculate button. The program calculates the mileage efficiency, as expected. Now enter the value 0 in the Gallons of gas used field and run the program. Instead of abruptly terminating as in the earlier case, the program shows a message about the DivideByZeroException exception, as shown in Figure 3.4, and it continues running. Now enter some alphabetic characters instead of number in the fields and click the Calculate button. This time you get a FormatException exception, and the program continues to run. Now try entering very large values in both the fields. If the values are large enough, the program encounters an OverflowException exception, but because the program is catching all types of exceptions, it continues running.

Figure 3.4Figure 3.4 To get information about an exception, you can catch the Exception object and access its Message property.

NOTE

checked and unchecked Visual C# .NET provides the checked and unchecked keywords, which can be used to enclose a block of statements (for example, checked {a = c/d}) or as an operator when you supply parameters enclosed in parentheses (for example, unchecked(c/d)). The checked keyword enforces checking of any arithmetic operation for overflow exceptions. If constant values are involved, they are checked for overflow at compile time. The unchecked keyword suppresses the overflow checking and instead of raising an OverflowException exception, the unchecked keyword returns a truncated value in case of overflow.

If checked and unchecked are not used, the default behavior in C# is to raise an exception in case of overflow for a constant expression or truncate the results in case of overflow for the nonconstant expressions.

The program in Step by Step 3.2 displays a message box when an exception occurs; the StackTrace property lists the methods in the reverse order of their calling sequence. This helps you understand the logical flow of the program. You can also place any appropriate error handling code in place, and you can display a message box.

When you write a catch block that catches exceptions of type Exception, the program catches all CLS-compliant exceptions. This includes all exceptions, unless you are interacting with legacy COM or Windows 32-bit Application Programming Interface (Win32 API) code. If you want to catch all kinds of exceptions, whether CLS-compliant or not, you can place a catch block with no specific type. A catch block like this must be the last catch block in the list of catch blocks because it is the most generic one.

NOTE

Do Not Use Exceptions to Control the Normal Flow of Execution Using exceptions to control the normal flow of execution can make your code difficult to read and maintain because the use of try-catch blocks to deal with exceptions forces you to fork the regular program logic between two separate locations—the try block and the catch block.

You might be thinking that it is a good idea to catch all sorts of exceptions in your code and suppress them as soon as possible. But it is not a good idea. A good programmer catches an exception in code only if he or she can answer yes to one or more of the following questions:

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

  • Will I log the exception information in the system event log or another 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 answer no to all these questions, then you should not catch the exception but rather just let it go. In that case, the exception propagates up to the calling code, and the calling code might have a better idea of how to handle the exception.

The throw Statement

A throw statement explicitly generates an exception in code. You use throw when a particular path in code results in an anomalous situation.

You should not throw exceptions for anticipated cases such as the user entering an invalid username or password; instead, you can handle this in a method that returns a value indicating whether the login is successful. If you do not have the correct permissions to read records from the user table and you try to read those records, an exception is likely to occur because a method for validating users should normally have read access to the user table.

WARNING

Use throw Only When Required The throw statement is an expensive operation. Use of throw consumes significant system resources compared to just returning a value from a method. You should use the throw statement cautiously and only when necessary because it has the potential to make your programs slow.

There are two ways you can use the throw statement. In its simplest form, you can just rethrow the exception in a catch block:

catch(Exception e)
{
  //TODO: Add code to create an entry in event log
  throw;
}

This usage of the throw statement rethrows the exception that was just caught. It can be useful in situations in which you don't want to handle the exception yourself but would like to take other actions (for example, recording the error in an event log, sending an email notification about the error) when an exception occurs and then pass the exception as-is to its caller.

The second way to use the throw statement is to use it to throw explicitly created exceptions, as in this example:

string strMessage =
  "EndDate should be greater than the StartDate";
ArgumentOutOfRangeException newException =
  new ArgumentOutOfRangeException(strMessage);
throw newException;

In this example, I first create a new instance of the ArgumentOutOfRangeException object and associate a custom error message with it, and then I throw the newly created exception.

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

Another way of throwing an exception is to throw it after wrapping it with additional useful information, as in this example:

catch(ArgumentNullException ane)
{
  //TODO: Add code to create an entry in the log file
  string strMessage = "CustomerID cannot be null";
  ArgumentNullException newException =
    new ArgumentNullException(strMessage, ane);
  throw newException;
} 

TIP

Custom Error Messages When you create an exception object, you should use its constructor that allows you to associate a custom error message rather than use its default constructor. The custom error message can pass specific information about the cause of the error and a possible way to resolve it.

Many times, you need to catch an exception that you cannot handle completely. In such a case you should perform any required processing and throw a more relevant and informative exception to the caller 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 caller code then has more information available to handle the exception appropriately.

It is interesting to note that because InnerException is of type Exception, it also has an InnerException property that may store a reference to another exception object. Therefore, when you throw an exception that stores a reference to another exception in its InnerException property, you are actually propagating a chain of exceptions. This information is very valuable at the time of debugging and allows you to trace the path of a problem to its origin.

The finally Block

The finally block contains code that always executes, whether or not any exception occurs. You use the finally block to write cleanup code that maintains your application in a consistent state and preserves sanitation in the environment. For example, you can write code to close files, database connections, and related input/output resources in a finally block.

TIP

No Code in Between try-catch-finally Blocks When you write try, catch, and finally blocks, they should be in immediate succession of each other. You cannot write any other code between the blocks, although compilers allow you to 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 the finally Block

  1. Add a new Windows form to the project. Name it StepByStep3_3.

  2. Place two TextBox controls (txtFileName and txtText), two Label controls (keep their default names), and a Button control (btnSave) on the form and arrange them as shown in Figure 3.5.

Figure 3.5Figure 3.5 When you click the Save button, the code in finally block executes, regardless of any exception in the try block.

  1. Attach the Click event handler to the btnSave control and add the following code to handle the Click event:

    private void btnSave_Click(
      object sender, System.EventArgs e)
    {
      // a StreamWriter writes characters to a stream
      StreamWriter sw = null;
      try
      {
        sw = new StreamWriter(txtFileName.Text);
        // Attempt to write the text box
        // contents in a file
        foreach(string line in txtText.Lines)
          sw.WriteLine(line);
        // This line only executes if there
        // were no exceptions so far
        MessageBox.Show(
         "Contents written, without any exceptions");
      }
      //catches all CLS-compliant exceptions
      catch(Exception ex)
      {
        string msg = String.Format(
          "Message: {0}\n Stack Trace:\n {1}",
          ex.Message, ex.StackTrace);
        MessageBox.Show(msg, ex.GetType().ToString());
        goto end;
      }
      // finally block is always executed to make sure
      // that the resources get closed whether or not
      // the 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 goto label
      finally
      {
        if (sw != null)
          sw.Close();
        MessageBox.Show("Finally block always " +
         "executes whether or not exception occurs");
      }
    end:
      MessageBox.Show("Control is at label: end");

    }

  2. Insert a Main() method to launch the form. Set the form as the startup object for the project.

  3. Run the project. You should see a Windows form, as shown in Figure 3.5. Enter a filename and some text. Watch the order of messages. Note that the message box being displayed in the finally block is always displayed prior to the message box displayed by the end label.

TIP

The finally Block Always Executes If you have a finally block associated with a try block, the code in the finally block always executes, whether or not an exception occurs.

Step by Step 3.3 illustrates that the finally block always executes. In addition, if there is a transfer-control statement such as goto, break, or continue in either the try block or the catch block, the control transfer happens after the code in the finally block is executed. What happens if there is a transfer-control statement in the finally block also? That is not an issue because the C# compiler does not allow you to put a transfer-control statement such as goto inside a finally block.

One of the ways the finally statement can be used is in the form of a try-finally block without any catch block. Here is an example:

try
{
  //Write code to allocate some resources
}
finally
{
  //Write code to Dispose all allocated resources
}

NOTE

Throwing Exceptions from the finally Block Although it is perfectly legitimate to throw exceptions from a finally block, it is not recommended. The reason for this is that when you are processing a finally block, you might already have an unhandled exception waiting to be caught.

This use ensures that allocated resources are properly disposed of, no matter what. In fact, C# provides a using statement that does the exact same job but with less code. A typical use of the using statement is as follows:

// Write code to allocate some resource. List the
// allocate resources in a comma-separated list inside
// the parentheses, with the following using block
using(...)
{
 //use the allocated resource
}
// Here, the Dispose() method is called for all the
// objects referenced in the parentheses of the
// using statement. There is no need to write
// any additional code
  • An exception occurs when a program encounters any unexpected problem during normal execution.

  • The FCL provides two main types of exceptions: SystemException and ApplicationException. SystemException represents the exceptions thrown by the CLR, and ApplicationException represents the exceptions thrown by the applications.

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

  • The try block consists of code that may raise an exception. A try block cannot exist on its own. It should be immediately followed by one or more catch blocks or a finally block.

  • The catch block handles the exception raised by the code in the try block. The CLR looks for a matching catch block to handle the exception; this is the first catch block with either the exact same exception or any of the exception's base classes.

  • If there are multiple catch blocks associated with a try block, the catch blocks should be arranged in specific-to-general order of exception types.

  • The throw statement is used to raise an exception.

  • The finally block is used to enclose code that needs to run, regardless 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