13.1 Introduction

In this chapter, we take a deeper look at exception handling. As you know from Section 8.5, an exception indicates that a problem occurred during a program’s execution. The name “exception” comes from the fact that, although the problem can occur, it occurs infrequently. As we showed in Section 8.5 and in Chapter 10, exception handling enables you to create apps that can handle exceptions—in many cases allowing a program to continue executing as if no problems had been encountered. More severe problems may prevent a program from continuing normal execution, instead requiring it to notify the user of the problem, then terminate in a controlled manner. The features presented in this chapter enable you to write clear, robust and more fault-tolerant programs (i.e., programs that are able to deal with problems that may arise and continue executing). “Best practices” for exception handling in Visual C# are specified in the Visual Studio documentation.1

After reviewing exception-handling concepts and basic exception-handling techniques, we overview .NET’s exception-handling class hierarchy. Programs typically request and release resources (such as files on disk) during program execution. Often, the supply of these resources is limited, or the resources can be used by only one program at a time. We demonstrate a part of the exception-handling mechanism that enables a program to use a resource, then guarantee that it will be released for use by other programs, even if an exception occurs. We show several properties of class System.Exception (the base class of all exception classes) and discuss how you can create and use your own exception classes.

You’ll see various C# features for working with values that can be null, including:

  • C# 6’s null-conditional operator (?.), which determines whether a reference is null before using it to call a method or access a property.

  • The null-coalescing operator (??), which returns its left operand’s value if it’s not null and returns its right operand’s value, otherwise.

  • Nullable types, which specify that a value-type variable may contain a value or null.

Finally, we’ll present C# 6’s exception filters that specify a condition for catching an exception.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset