Home Random Page


CATEGORIES:

BiologyChemistryConstructionCultureEcologyEconomyElectronicsFinanceGeographyHistoryInformaticsLawMathematicsMechanicsMedicineOtherPedagogyPhilosophyPhysicsPolicyPsychologySociologySportTourism






Exceptions and State Management

In this chapter:

Defining “Exception”............................................................................ 452

Exception-Handling Mechanics.............................................................. 453

TheSystem.Exception Class..................................................... 460

FCL-Defined Exception Classes............................................................... 463

Throwing an Exception........................................................................... 466

Defining Your Own Exception Class......................................................... 467

Trading Reliability for Productivity......................................................... 469

Guidelines and Best Practices............................................................... 478

Unhandled Exceptions.......................................................................... 485

Debugging Exceptions.......................................................................... 490

Exception-Handling Performance Considerations.................................. 492

Constrained Execution Regions (CERs).................................................. 494

Code Contracts..................................................................................... 498

 

This chapter is all about error handling. But it’s not just about that. There are several parts to error handling. First, we’ll define what an error actually is. Then, we’ll talk about how to discover when your code is experiencing an error and about how to recover from this error. At this point, state becomes an issue because errors tend to come at inopportune times. It is likely that your code will be in the middle of mutating some state when it experiences the error, and your code likely will have to restore some state back to what it was prior to attempting to mutate it. Of course, we’ll also talk about how your code can notify its callers that it has detected an error.

In my opinion, exception handling is the weakest area of the common language runtime (CLR) and therefore causes many problems for developers writing managed code. Over the years, Microsoft has made some significant improvements to help developers deal with errors, but I believe that there

is much more that must be done before we can really have a good, reliable system. I will talk a lot about the various enhancements that have been made when dealing with unhandled exceptions, constrained execution regions, code contracts, runtime wrapped exceptions, uncatchable exceptions, and so on.


 
 

Defining “Exception”

When designing a type, you first imagine the various situations in which the type will be used. The type name is usually a noun, such as FileStream or StringBuilder. Then you define the proper- ties, methods, events, and so on for the type. The way you define these members (property data types, method parameters, return values, and so forth) becomes the programmatic interface for your type. These members indicate actions that can be performed by the type itself or on an instance of the type. These action members are usually verbs such as Read, Write, Flush, Append, Insert, Remove, etc. When an action member cannot complete its task, the member should throw an exception.



       
   
 
 

 

Look at the following class definition.

 

internal sealed class Account {

public static void Transfer(Account from, Account to, Decimal amount) { from ­= amount;

to += amount;

}

}

 

The Transfer method accepts two Account objects and a Decimal value that identifies an amount of money to transfer between accounts. Obviously, the goal of the Transfer method is to subtract money from one account and add money to another. The Transfer method could fail for many reasons: the from or to argument might be null; the from or to argument might not refer to an open account; the from account might have insufficient funds; the to account might have so much money in it that adding more would cause it to overflow; or the amount argument might be 0, nega- tive, or have more than two digits after the decimal place.

When the Transfer method is called, its code must check for all of these possibilities, and if any of them are detected, it cannot transfer the money and should notify the caller that it failed by throw- ing an exception. In fact, notice that the Transfer method’s return type is void. This is because the Transfer method has no meaningful value to return; if it returns at all, it was successful. If it fails, it throws a meaningful exception.

Object-oriented programming allows developers to be very productive because you get to write code like this.

 

Boolean f = "Jeff".Substring(1, 1).ToUpper().EndsWith("E"); // true

 

Here I’m composing my intent by chaining several operations together.1 This code was easy for me to write and is easy for others to read and maintain because the intent is obvious: take a string, grab

 

 
 

1 In fact, C#’s extension method feature exists in the language to allow you to chain more methods together that would not have been chainable otherwise.


a portion of it, uppercase that portion, and see if it ends with an “E.” This is great, but there is a big assumption being made here: no operation fails. But, of course, errors are always possible, so we need a way to handle those errors. In fact, there are many object-oriented constructs—constructors, get- ting/setting a property, adding/removing an event, calling an operator overload, calling a conversion operator—that have no way to return error codes, but these constructs must still be able to report

an error. The mechanism provided by the Microsoft .NET Framework and all programming languages that support it is called exception handling.

       
   
 
 

 

 


Date: 2016-03-03; view: 630


<== previous page | next page ==>
Nbsp;   The CLR Has Special Support for Nullable Value Types | Nbsp;   Exception-Handling Mechanics
doclecture.net - lectures - 2014-2024 year. Copyright infringement or personal data (0.008 sec.)