Добавил:
Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
C# and the NET Platform, Second Edition - Andrew Troelsen.pdf
Скачиваний:
67
Добавлен:
24.05.2014
Размер:
22.43 Mб
Скачать

Catching ExceptionsC# and the .NET Platform, Second Edition

by Andrew Troelsen

ISBN:1590590554

Because the SpeedUp() method now throws an exception, you need to be ready to handle the exception

Apress © 2003 (1200 pages)

should it occur (you'll see what happens if you fail to catch an exception a bit later in this chapter). When

This comprehensive text starts with a brief overview of the

you are calling a C#methodlanguagethat mayand thenthrowquicklyan exception,moves toyoukeymaketechnicaluseandof a try/catch block. Once you have caught the exceptionarchitecturaltype, youissuaresablefor .NETto invokedev lofpersthe. members of the System.Exception type. What you do with this information is largely up to you. You may wish to log this information to a given file, write the error to the Windows event log, or display the message to the end user. Here, you will simply dump the

Table of Contents

contents to the console window:

C# and the .NET Platform, Second Edition

Introduction

// Speed up the car safely...

Part One - Introducing C# and the .NET Platform

public static int Main(string[] args)

Chapter 1 - The Philosophy of .NET

{

Chapter 2 - Building C# Applications

// Make a car.

Part Two - The C# Programming Language

Car buddha = new Car("Buddha", 100, 20);

Chapter 3 - C# Language Fundamentals

// Speed up past the car's max speed to

Chapter 4 - Object-Oriented Programming with C#

// trigger the exception.

Chapter try5 - Exceptions and Object Lifetime

Chapter {6 - Interfaces and Collections

Chapter 7 - Callbackfor(intIn erfaces,i = 0;Delegates,i < 10;andi++)Events

buddha.SpeedUp(10);

Chapter 8 - Advanced C# Type Construction Techniques

}

Part Three - Programming with .NET Assemblies

catch(Exception e)

Chapter 9 - Understanding .NET Assemblies

{

Chapter 10 - Processes, AppDomains, Contexts, and Threads

Console.WriteLine("\n*** Error! ***");

Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming

Console.WriteLine("Method: {0}", e.TargetSite);

Part Four - Leveraging the .NET Libraries

Console.WriteLine("Message: {0}", e.Message);

Chapter 12 - Object Serialization and the .NET Remoting Layer

Console.WriteLine("Source: {0}", e.Source);

Chapter 13 - Building a Better Window (Introducing Windows Forms)

}

Chapter 14 - A Better Painting Framework (GDI+)

// The error has been handled, continue on with the flow of this app...

Chapter 15 - Programming with Windows Forms Controls

Console.WriteLine("\n***** Out of exception logic *****");

Chapter 16 - The System.IO Namespace return 0;

Chapter 17 - Data Access with ADO.NET

}

Part Five - Web Applications and XML Web Services

Chapter 18 - ASP.NET Web Pages and Web Controls

ChapterIn essence,19 - ASPa try.NETblockWebis aApplicationssection of code that is on the lookout for any exception that may be Chapterencountered20 - XMLduringWebitsServicesscope. If an exception is detected, the flow of program execution is sent to the

appropriate catch block. On the other hand, if the code within a try block does not trigger an exception, the

Index

catch block is skipped entirely, and all is right with the world. Figure 5-1 shows a test run of the handled

List of Figures

error.

List of Tables

Edition

ISBN:1590590554

brief overview of the

key technical and

.

Table

C# and

Part

Chapter

Chapter

Part Two - The C# Programming Language

Figure 5-1: Dealing with the error using structured exception handling

Chapter 3 - C# Language Fundamentals

Chapter 4 - Object-Oriented Programming with C#

As you can see, once an exception has been handled, the application is free to continue on from the point

Chapter 5 - Exceptions and Object Lifetime

after the catch block. In some circumstances, a given exception may be critical enough to warrant the

Chapter 6 - Interfaces and Collections

termination of the application. However, in a good number of cases, the logic within the exception handler Chapterwill ensure7 -theCallbackapplicationInterfaces,will beDelegates,able to continuea d Ev ntson its merry way (although it may be slightly less

Chapterfunctional,8 -suchAdvancedas theC#caseTypeofConstructionnot being ableT chniquesto connect to a remote data source).

Part Three - Programming with .NET Assemblies

Chapter 9 - Understanding .NET Assemblies

The TargetSite Property

Chapter 10 - Processes, AppDomains, Contexts, and Threads

ChapterAs you11have- Typejust seen,R flection,the SystemLate Binding,.Exceptionand .AttribuTargetSite-BasedpropertyPrograllowsmmingyou to determine the name of the

PartmethodFour that- Levethrewagingthethecurrent.NET Librariesexception. Understand, however, that TargetSite does not simply return a

Chvanillapter-12flavored- Objectstring,Serializationbut stroandglythetyped.NETSystemRemoting.ReflectionLayer .MethodBase class. This abstract type can be

Chapterused to13gather- Buildingnumerousa BetterdetailsW ndowregarding(Introducingthe offendingWi owsmethodForms) as well as the class that defines the Chapteroffending14 method- A Better. ToPaintingillustrate,Frameworkassume(GDI+)the previous catch logic has been updated as follows:

Chapter 15 - Programming with Windows Forms Controls

Chcatch(Exceptionpter 16 - The Systeme).IO Namespace

Chapter{ 17 - Data Access with ADO.NET

Part FiveConsole- Web Applications.WriteLine("\n***a d XML Web SeError!vices ***");

Chapter Console18 - ASP.NET.WriteLine("ClassWeb Pag and Web Controlsdefining member: {0}",

e.TargetSite.DeclaringType);

Chapter 19 - ASP NET Web Applications

Console.WriteLine("Member type: {0}", e.TargetSite.MemberType);

Chapter 20 - XML Web Services

Index Console.WriteLine("Member name: {0}", e.TargetSite);

Console.WriteLine("Message: {0}", e.Message);

List of Figures

Console.WriteLine("Source: {0}", e.Source);

List of Tables

}

This time, you make use of the MethodBase.DeclaringType property to determine the fully qualified name of the class that threw the error (SimpleException.Car in this case) as well as the MethodBase.MemberType property to identify the type of member (such as a property versus a method) where this exception originated. Figure 5-2 shows the updated output.

Edition

ISBN:1590590554

brief overview of the

key technical and

.

Table

C# and

Part

Chapter

Chapter

Part

Chapter

ChapterFigure4 - 5Object-2: Obta-Orientedning detailedProgrammingerror informationwith C#

Chapter 5 - Exceptions and Object Lifetime

Chapter 6 - Interfaces and Collections

As you may be aware, the ability to discover information regarding the structure of a type is a form of RTTI

Chapter 7 - Callback Interfaces, Delegates, and Events

(runtime type identification). The .NET base class library supplies an entire namespace devoted to the

Chapter 8 - Advanced C# Type Construction Techniques

topic of RTTI named System.Reflection (in fact, MethodBase is defined within System.Reflection). Chapter

Part Three - Programming with .NET Assemblies

11 will examine the details of .NET reflection services. For the time being, simply understand that the

Chapter 9 - Understanding .NET Assemblies

System.Exception.TargetSite property allows you to discover a number of details about the method that

Chapttriggeredr 10 - Processes, AppDomains, Contexts, and Threads

the exception at hand.

Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming

Part Four - Leveraging the .NET Libraries

The StackTrace Property

Chapter 12 - Object Serialization and the .NET Remoting Layer

Chapter 13 - Building a Better Window (Introducing Windows Forms)

In addition to identifying the type and member that threw a given exception via TargetSite, the

ChaptSystemr 14 - A Better Painting Framework (GDI+)

.Exception.StackTrace property allows you to identify the series of calls that resulted in the Chapterexception15.-ToProgrammingillustrate, assumewith Windowsyou haveFormsonceControlsagain updated your catch logic:

Chapter 16 - The System.IO Namespace

Chapter 17 - Data Access with ADO.NET catch(Exception e)

Part Five - Web Applications and XML Web Services

{

Chapter 18 - ASP.NET Web Pages and Web Controls

...

Chapter 19 - ASP.NET Web Applications StackTrace

Console.WriteLine("Stack: {0}", e. );

Chapter} 20 - XML Web Services

Index

List of Figures

If you were to run the program, you would find the following line printed to the console (assuming the

List of Tables

application is located under the C:\MyApps\Exception directory):

Stack: at SimpleException.Car.SpeedUp(Int32 delta)

in c:\myapps\exceptions\car.cs:line 65

at Exceptions.App.Main()

in c:\myapps\exceptions\app.cs:line 21

As you can see, the System.String returned from StackTrace documents the sequence of calls that resulted in the throwing of this exception. Notice how the bottommost line number of this string identifies the first call in the sequence, while the topmost line number identifies the exact location of the offending member. Clearly, this information can be quite helpful during the debugging of a given application, as you are able to "follow the flow" of the error's origin.

The HelpLink Property

While the TargetSite and StackTrace properties allow programmers to gain an understanding of a given

C# and the .NET Platform, Second Edition

exception, this information is of little use to the end user. As you have already seen, the by Andrew Troelsen ISBN:1590590554

System.Exception.Message property can be used to obtain human-readable information that may be

Apress © 2003 (1200 pages)

displayed to the current user. In addition, the HelpLink property can be set to point the user to a given URL

This comprehensive text starts with a brief overview of the or standard Win32 help file that contains more detailed information.

C# language and then quickly moves to key technical and

architectural issues for .NET developers.

By default, the value managed by the HelpLink property is an empty string. If you wish to fill this property with a relevant value, you will need to do so before throwing the System.Exception type. Here is the

relevant update to the SpeedUp() method:

Table of Contents

C# and the .NET Platform, Second Edition

if(carIsDead)

Introduction

{

Part One - Introducing C# and the .NET Platform

Exception ex = new Exception("Error information can be found at:");

Chapter 1 - The Philosophy of .NET

ex.HelpLink = "http://www.CarsRUs.com";

Chapter 2 - Building C# Applications

throw ex;

Part Two - The C# Programming Language

}

Chapter 3 - C# Language Fundamentals

Chapter 4 - Object-Oriented Programming with C#

Chapter 5 - Exceptions and Object Lifetime

The catch logic, of course, would print out this help link information as follows:

Chapter 6 - Interfaces and Collections

Chapter 7 - Callback Interfaces, Delegates, and Events catch(Exception e)

Chapter 8 - Advanced C# Type Construction Techniques

{

Part Three - Programming with .NET Assemblies

...

Chapter 9 - Understanding .NET Assemblies

Console.WriteLine("Help Link: {0}", e.HelpLink);

Chapter 10 - Processes, AppDomains, Contexts, and Threads

}

Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming

Part Four - Leveraging the .NET Libraries

Chapter 12 - Object Serialization and the .NET Remoting Layer

ChapterSOURCE13 - Building aTheBetterSimpleExceptionWindow (IntroducingprojectWindowsis includedForms)under the Chapter 5 subdirectory.

CODE

Chapter 14 - A Better Painting Framework (GDI+)

Chapter 15 - Programming with Windows Forms Controls

Chapter 16 - The System.IO Namespace

Chapter 17 - Data Access with ADO.NET

Part Five - Web Applications and XML Web Services

Chapter 18 - ASP.NET Web Pages and Web Controls

Chapter 19 - ASP.NET Web Applications

Chapter 20 - XML Web Services

Index

List of Figures

List of Tables

List of Tables
List of Figures

CLR SystemC#-Leveland the .ExceptionsNET Platform, Second(SystemEdition.SystemException)

by Andrew Troelsen

ISBN:1590590554

As mentioned, the .NET base class libraries already define a number of exception classes. For example,

Apress © 2003 (1200 pages)

the System namespace defines numerous general exception types such as

This comprehensive text starts with a brief overview of the

ArgumentOutOfRangeException,C# language and IndexOutOfRangeException,then quickly moves to key technicalStackOverflowException,and and so forth. Other namespacesarchitecturdefine additionall issues forexceptions.NET developethat reflects. the behavior of that namespace (e.g., System.Drawing.Printing defines printing exceptions, System.IO defines IO-based exceptions, System.Data defines data-centric exceptions, and so forth).

Table of Contents

C#Exceptionsand the .NETthatPlatform,are thrownSecondby methodsEdition in the base class libraries are (appropriately) called system

exceptions. System exceptions generally (but sadly not always) derive directly from a base class named

Introduction

System.SystemException, which in turn derives from System.Exception (which of course derives from

Part One - Introducing C# and the .NET Platform

System.Object):

Chapter 1 - The Philosophy of .NET

Chapter 2 - Building C# Applications

PartpublicTwo - TheclassC# ProgrammingSystemExceptionLanguage: Exception,

ChapterISerializable3 - C# Language Fundamentals

{

Chapter 4 - Object-Oriented Programming with C#

public SystemException();

Chapter 5 - Exceptions and Object Lifetime

public SystemException(string message);

Chapter 6 - Interfaces and Collections

public SystemException(string message, Exception innerException);

Chapter 7 - Callback Interfaces, Delegates, and Events

public string HelpLink { virtual get; virtual set; }

Chapter 8 - Advanced C# Type Construction Techniques

public Exception InnerException { get; }

Part Three - Programming with .NET Assemblies

public string Message { virtual get; }

Chapter 9 - Understanding .NET Assemblies

public string Source { virtual get; virtual set; }

Chapter 10 - Processes, AppDomains, Contexts, and Threads public string StackTrace { virtual get; }

Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming public MethodBase TargetSite { get; }

Part Four - Leveraging the .NET Libraries

public virtual bool Equals(object obj);

Chapter 12 - Object Serialization and the .NET Remoting Layer public virtual Exception GetBaseException();

Chapter 13 - Building a Better Window (Introducing Windows Forms) public virtual int GetHashCode();

Chapter 14 - A Better Painting Framework (GDI+) public virtual void

Chapter 15 - Programming with Windows Forms Controls

GetObjectData(SerializationInfo info, StreamingContext context);

Chapter 16 - The System.IO Namespace

public Type GetType();

Chapterpublic17 - DatavirtualAccess withstringADO.NETToString();

Part} Five - Web Applications and XML Web Services

Chapter 18 - ASP.NET Web Pages and Web Controls

Chapter 19 - ASP.NET Web Applications

Given that the System.SystemException type does not add any additional functionality beyond that of

Chapter 20 - XML Web Services

System.Exception, you might wonder why SystemException exists in the first place. The idea is that when

Index

an exception type derives from System.SystemException, you are able to determine that the .NET runtime is the entity that has thrown the exception, rather than the custom code base of the executing application. As you will see in just a bit, however, there is a lack of consistency within the .NET base class libraries regarding this pattern.

Locating System Exceptions

While it is nice to know that System.SystemException provides a way to identify the underlying source of the error, the next logical question would be "How do I know which exceptions may be thrown by a given base class library method?" The ultimate answer to that question is simple: Use online help. For example, if you were to look up the File.Open() method, you would find a table that describes the set of possible system exceptions that may be thrown should an error occur (Figure 5-3).

ISBN:1590590554

of the

and

Table

C# and

Part

Chapter

Chapter

Part

Chapter

Chapter

Chapter

Chapter

Chapter

Chapter

Part

Chapter

Chapter

Chapter Programming

Part Four - Leveraging the .NET Libraries

Figure 5-3: Identifying the exceptions thrown from a given method

Chapter 12 - Object Serialization and the .NET Remoting Layer

Chapter 13 - Building a Better Window (Introducing Windows Forms)

For those coming to .NET from a Java mindset, understand that a method is not prototyped with the set of

Chapter 14 - A Better Painting Framework (GDI+)

exceptions it may emit. Therefore you are not required to handle each and every possible exception that

Chapter 15 - Programming with Windows Forms Controls

may be thrown from a given member. As you will see in just a bit, if you fail to handle a raised exception,

Chapter 16 - The System.IO Namespace

the operating system will trigger a "last chance exception."

Chapter 17 - Data Access with ADO.NET

Part Five - Web Applications and XML Web Services

Chapter 18 - ASP.NET Web Pages and Web Controls

Chapter 19 - ASP.NET Web Applications

Chapter 20 - XML Web Services

Index

List of Figures

List of Tables

Custom ApplicationC# and he .NET-LevelPlatform,ExceptionsS cond Edition(System.ApplicationException)

by Andrew Troelsen

ISBN:1590590554

Now that you understand the proposed role of System.SystemException (to identify CLR exceptions), you

Apress © 2003 (1200 pages)

may wonder if it is possible to build custom exceptions for use within your proprietary applications. The

This comprehensive text starts with a brief overview of the

answer is a resoundingC# language"yes."aIndfact,thenthequickly.NETmovesbase classto keylibrarytechnicaldefinesand another System.Exception derived type named (appropriatelyarchitecturalenough)issues forSystem.NET.ApplicationException:developers.

public class ApplicationException : Exception,

Table of Contents

ISerializable

C# and the .NET Platform, Second Edition

{

Introduction

public ApplicationException();

Part One - Introducing C# and the .NET Platform

public ApplicationException(string message);

Chapter 1 - The Philosophy of .NET

public ApplicationException(string message, Exception innerException);

Chapter 2 - Building C# Applications

public string HelpLink { virtual get; virtual set; }

Part Two - The C# Programming Language

public Exception InnerException { get; }

Chapter 3 - C# Language Fundamentals

public string Message { virtual get; }

Chapter 4 - Object-Oriented Programming with C#

public string Source { virtual get; virtual set; }

Chapterpublic5 - ExceptionsstringandStackTraceObject Lifetime{ virtual get; }

Chapterpublic6 - InterfacesMethodBaseand CollectionsTargetSite { get; }

Chapterpublic7 - CallbackvirtualInterfaces,boolDelegates,Equals(objectand Eventsobj);

public virtual Exception GetBaseException();

Chapter 8 - Advanced C# Type Construction Techniques

public virtual int GetHashCode();

Part Three - Programming with .NET Assemblies

public virtual void

Chapter 9 - Understanding .NET Assemblies

GetObjectData(SerializationInfo info, StreamingContext context);

Chapter 10 - Processes, AppDomains, Contexts, and Threads

public Type GetType();

Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming

public virtual string ToString();

Part Four - Leveraging the .NET Libraries

}

Chapter 12 - Object Serialization and the .NET Remoting Layer Chapter 13 - Building a Better Window (Introducing Windows Forms)

Chapter 14 - A Better Painting Framework (GDI+)

Like SystemException, ApplicationException does not add any additional functionality beyond the inherited

Chapter 15 - Programming with Windows Forms Controls

members of System.Exception. Again, the only real role of System.ApplicationException is to identify the

Chapter 16 - The System.IO Namespace

underlying source of the error. When you handle an exception deriving from System.ApplicationException, Chapteryou can17(ideally)- Data AccessassumewiththeADOexception.NET was raised by the code base of the executing application, rather than

Partby theFive.NET- WebbaseApplicationsclass librariesnd XML. Web Services

Chapter 18 - ASP.NET Web Pages and Web Controls

Figure 5-4 illustrates the relationship between these key exception-centric base classes.

Chapter 19 - ASP.NET Web Applications

Chapter 20 - XML Web Services

Index

List of Figures

List of Tables

Edition

ISBN:1590590554

brief overview of the

key technical and

.

Table

C# and

Part

Chapter

Chapter

Part

Chapter

Chapter

Chapter

Chapter 6 - Interfaces and Collections

Figure 5-4: Application and system exceptions

Chapter 7 - Callback Interfaces, Delegates, and Events

Chapter 8 - Advanced C# Type Construction Techniques

PartStrictlyThreespeaking,- Programmiwhengyouwithcreate.NET Assembliesyour own custom .NET exception types, you are not required to derive Chapterfrom System9 - Understandi.ApplicationExceptiong .NET Assemblies. If you so choose, you are able to simply derive from the more generic

System.Exception (and if you really wanted to, nothing would stop you from deriving from

Chapt r 10 - Processes, AppDomains, Contexts, and Threads

System.SystemException . . . but don't do so!). To understand the various possibilities, let's build a custom

Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming

exception type.

Part Four - Leveraging the .NET Libraries

Chapter 12 - Object Serialization and the .NET Remoting Layer

ChapterBuilding13 - BuildingCustoma BetterExceptions,Window (IntroducingTakeWindowsOneForms)

Chapter 14 - A Better Painting Framework (GDI+)

Although you could simply throw instances of System.Exception to signal a runtime error (as seen in the

Chapter 15 - Programming with Windows Forms Controls

previous example), it is sometimes advantageous to build a custom class that encapsulates the unique

Chapter 16 - The System.IO Namespace

details of your problem. For example, assume you wish to build a custom exception to represent the error of

Chapter 17 - Data Access with ADO.NET

speeding up a doomed automobile.

Part Five - Web Applications and XML Web Services

Chapter 18 - ASP.NET Web Pages and Web Controls

The first approach we will look at involves defining a new class derived directly from System.Exception (by

Chapter 19 - ASP.NET Web Applications

convention, all exception types end with an "Exception" suffix). Like any class, you are free to include any

Chapter 20 - XML Web Services

custom properties, methods, or fields that can be used from within the catch block of the calling logic. You

Indarexalso free to override any virtual members defined by your parent class:

List of Figures

List of Tables

// This custom exception describes the details of the car-is-dead condition.

public class CarIsDeadException : System.Exception

{

//This custom exception maintains the name of the doomed car. private string carName;

public CarIsDeadException(){ }

public CarIsDeadException(string carName)

{

this.carName = carName;

}

//Override the Exception.Message property.

public override string Message

{

get

{

string msg = base.Message;

if(carName != null)

 

C# and the .NET Platform, Second Edition

 

 

msg += carName + " has bought the farm...";

 

by Andrew Troelsen

ISBN:1590590554

}

return msg;

 

Apress © 2003 (1200 pages)

 

}

This comprehensive text starts with a brief overview of the

C# language and then quickly moves to key technical and

}

architectural issues for .NET developers.

 

Here, the CarIsDeadException type maintains a private data member that holds the pet name of the car that

Table of Contents

threw the exception. You have also added two constructors to the class, and overridden the virtual Message

C# and the .NET Platform, Second Edition

property in order to include the pet name of the car in the description. Throwing this error from within

Introduction

SpeedUp() is straightforward:

Part One - Introducing C# and the .NET Platform

Chapter 1 - The Philosophy of .NET

// Throw the custom CarIsDeadException.

Chapter 2 - Building C# Applications

public void SpeedUp(int delta)

Part Two - The C# Programming Language

{

Chapter 3 - C# Language Fundamentals

// If the car is dead, just say so...

Chapter 4 - Object-Oriented Programming with C# if(carIsDead)

Chapter 5 - Exceptions and Object Lifetime

{

Chapter 6 - Interfaces and Collections

// Throw 'car is dead' exception.

Chapter 7 - Callback Interfaces, Delegates, and Events

throw new CarIsDeadException(this.petName);

Chapter }8 - Advanced C# Type Construction Techniques

Part ThrelseProgramming// Notwithdead,.NET Assembliesspeed up.

Chapter {9

...- Understanding}

.NET Assemblies

Chapter}

10

- Processes, AppDomains, Contexts, and Threads

Chapter 11

- Type Reflection, Late Binding, and Attribute-Based Programming

Part Four - Leveraging the .NET Libraries

Catching the custom exception is just as easy:

Chapter 12 - Object Serialization and the .NET Remoting Layer

Chapter 13 - Building a Better Window (Introducing Windows Forms)

try

Chapter 14 - A Better Painting Framework (GDI+)

{... }

Chapter 15 - Programming with Windows Forms Controls

catch(CarIsDeadException e)

Chapter 16 - The System.IO Namespace

{

Chapter 17 - Data Access with ADO.NET

Console.WriteLine("Method: {0}", e.TargetSite);

Part Five - Web Applications and XML Web Services

Console.WriteLine("Message: {0}", e.Message);

Chapter 18 - ASP.NET Web Pages and Web Controls

}

Chapter 19 - ASP.NET Web Applications Chapter 20 - XML Web Services

Index

ListSo,ofnowFiguresthat you understand the basic process of defining a custom exception, you may wonder if you are

Listrequiredof Tablesto do so. Typically, you only need to create custom exceptions when the error is tightly bound to the class issuing the error (for example, a File class that throws a number of file-related errors, a Car class that throws a number of car-related errors, and so forth). In doing so, you provide the caller with the ability to handle numerous exceptions on a name-by-name basis (as seen in just a bit).

Building Custom Exceptions, Take Two

Our current CarIsDeadException type has overridden the System.Exception.Message property in order to configure a custom error message. This class also has an overloaded constructor that accepts the pet name of the automobile that has currently met its maker. As you build custom exceptions, you are able to build the type as you see fit. However, the recommended approach is to build a relatively simple type that supplies three named constructors matching the following signature:

public class CarIsDeadException : System.Exception

{

public CarIsDeadException(){ }

Chapter 14 - A Better Painting Framework (GDI+)
Chapter 13 - Building a Better Window (Introducing Windows Forms)

public CarIsDeadException(string message)

C# and the .NET Platform, Second Edition

 

: base(message){ }

ISBN:1590590554

by Andrew Troelsen

// Just in case the CarIsDeadException is generated by

Apress © 2003 (1200 pages)

// another exception, the previous exception can be passed in

This comprehensive text starts with a brief overview of the

// as a constructor parameter.

C# language and then quickly moves to key technical and

public CarIsDeadException(string message, Exception innerEx) architectural issues for .NET developers.

: base(message, innerEx){ }

}

Table of Contents

C# and the .NET Platform, Second Edition

Notice that this time you have not provided a private string to hold the pet name, and have not overridden the

Introduction

Message property. Rather, you are simply passing all the relevant information to your base class. When you

Part One - Introducing C# and the .NET Platform

wish to throw an exception of this type, you would send in all necessary information as a constructor

Chapter 1 - The Philosophy of .NET argument (the output would be identical):

Chapter 2 - Building C# Applications

Part Two - The C# Programming Language

public void SpeedUp(int delta)

Chapter 3 - C# Language Fundamentals

{

Chapter 4 - Object-Oriented Programming with C#

...

Chapter 5 - Exceptions and Object Lifetime if(carIsDead)

Chapter 6 - Interfaces and Collections

{

Chapter 7 - Callback Interfaces, Delegates, and Events

// Pass pet name and message as ctor argument.

Chapter 8 - Advancedthrow C#newTypeCarIsDeadException(thisConstruction T chn ques .petName + " has bought the farm!");

Part Three} - Programming with .NET Assemblies

Chapter else9 - Understanding// Not.NETdead,Assemblispeed up.

Chapter {10...- Processes,} AppDomains, Contexts, and Threads

}

Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming

Part Four - Leveraging the .NET Libraries

Chapter 12 - Object Serialization and the .NET Remoting Layer

Using this design, this custom exception is little more than a uniquely named class, devoid of any unnecessary member variables (or overrides). Don't be surprised if most (if not all) of your custom exception

classes follow this pattern. Many times, the role of a custom exception is not necessarily to provide additional

Chapter 15 - Programming with Windows Forms Controls

functionality beyond what is inherited from the base class, but to provide a strongly named type that clearly

Chapter 16 - The System.IO Namespace identifies the nature of the error.

Chapter 17 - Data Access with ADO.NET

Part Five - Web Applications and XML Web Services

Building Custom Exceptions, Take Three

Chapter 18 - ASP.NET Web Pages and Web Controls

Chapter 19 - ASP.NET Web Applications

Recall the exceptions can be categorized as system-level or application-level types. If you wish to clearly

Chapter 20 - XML Web Services

mark the fact that the CarIsDeadException is a type thrown by the application itself (rather than the base

Index

class libraries), you are free to retrofit the type definition as follows:

List of Figures

List of Tables

public class CarIsDeadException : ApplicationException

{

// Constructors for this custom exception. public CarIsDeadException(){ }

public CarIsDeadException(string message) : base(message){ }

public CarIsDeadException(string message, Exception innerEx) : base(message, innerEx){ }

}

Once you have done so, the logic that handles the CarIsDeadException is unchanged. Again, we'll look at the process of identifying the underlying nature of a generated exception in just a bit. Until then, let's check how to handle multiple exceptions.

for(int i = 0; i < 10; i++)

Handling MultipleC# and theExceptions.NET Pla f rm, Second Edition

by Andrew Troelsen

ISBN:1590590554

In its simplest form, a try block has a single corresponding catch block. In reality, you 23often run into a situatio

Apress © 2003 (1200 pages)

where the code within a try block could trigger numerous possible exceptions. For example, assume the car's

This comprehensive text starts with a brief overview of the

SpeedUp() methodC#notlanguageonly throwsand thenan quicklyexceptionmoveswhento youkey attempttechnicaltoandspeed up a doomed automobile, but thro a system-level exceptionarchitecturalif youissendues forin an.NETinvaliddevelopersparameter. (which for the sake of argument is any number les than zero):

Table of Contents

// Test for bad parameter.

C# and the .NET Platform, Second Edition

public void SpeedUp(int delta)

Introduction

{

Part One - Introducing C# and the .NET Platform

// Bad param? Throw system supplied exception!

Chapter 1 - The Philosophy of .NET if(delta < 0)

Chapter 2 - Building C# Applications

throw new ArgumentOutOfRangeException("Speed must be greater than zero!

Part Two - The C# Programming Language

if(carIsDead)

Chapter 3 - C# Language Fundamentals

{

Chapter 4 - Object-Oriented Programming with C#

// Throw 'Car is dead' application exception.

Chapter 5 - Exceptionsthrow newand ObjectCarIsDeadException(thisLif time .petName + " has bought the farm!");

Chapter }6 - Interfaces and Collections

Chapter ...7 - Callback Interfaces, Delegates, and Events

}

Chapter 8 - Advanced C# Type Construction Techniques

Part Three - Programming with .NET Assemblies

Chapter 9 - Understanding .NET Assemblies

Chapter 10 - Processes, AppDomains, Contexts, and Threads

The calling logic would look like this:

Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming

Part Four - Leveraging the .NET Libraries

// Here, we are on the lookout for multiple exceptions.

Chapter 12 - Object Serialization and the .NET Remoting Layer

try

Chapter 13 - Building a Better Window (Introducing Windows Forms)

{

Chapter 14 - A Better Painting Framework (GDI+)

Chapter 15 - Programming with Windows Forms Controls buddha.SpeedUp(10);

Chapter 16 - The System.IO Namespace

}

Chapter 17 - Data Access with ADO.NET catch(CarIsDeadException e)

Part Five - Web Applications and XML Web Services

{

Chapter 18 - ASP.NET Web Pages and Web Controls

Console.WriteLine("Method: {0}", e.TargetSite);

Chapter 19 - ASP.NET Web Applications

Console.WriteLine("Message: {0}", e.Message);

Chapter 20 - XML Web Services

}

Index ArgumentOutOfRangeException

catch( e)

List{ of Figures

List of TablesConsole.WriteLine("Method: {0}", e.TargetSite);

Console.WriteLine("Message: {0}", e.Message);

}

When you are constructing multiple catch blocks for a single try block, you must be aware that when an excepti is thrown, it will be processed by the "nearest available" catch. To illustrate exactly what the "nearest available" catch means, assume you retrofitted the previous catch logic as follows:

// This code will not compile! try

{

for(int i = 0; i < 10; i++) buddha.SpeedUp(10);

}

catch(Exception e)

{...}

C# and the .NET Platform, Second Edition

 

catch(CarIsDeadException e)

ISBN:1590590554

{...}

by Andrew Troelsen

Apress © 2003 (1200 pages)

 

catch(ArgumentOutOfRangeException e)

 

{...}

This comprehensive text starts with a brief overview of the

C# language and then quickly moves to key technical and

 

 

architectural issues for .NET developers.

This exception handling logic generates compile-time errors. The problem is due to the fact that the first catch

block can handle anything derived from System.Exception (given the "is-a" relationship), including the

Table of Contents

CarIsDeadException and ArgumentOutOfRangeException types. Therefore, the final two catch blocks are

C# and the .NET Platform, Second Edition

unreachable!

Introduction

PartTheOnerule-ofInthumbroducingto keepC# andin themind.NETis toPlatformmake sure your catch blocks are structured such that the very first catch

Chapterthe most1 specific- The Philosophyexceptionof(i..eNET., the most derived type in a given exception inheritance chain) while the final cat Chaptis thermost2 - generalBuilding (iC#.e.,Applicationsthe base class of a given exception inheritance chain, in this case System.Exception).

Part Two - The C# Programming Language

Therefore, if you wish to provide a catch statement that will handle any errors beyond CarIsDeadException and

Chapter 3 - C# Language Fundamentals

ArgumentOutOfRangeException, you would write the following:

Chapter 4

- Object-Oriented Programming with C#

Chapter 5

- Exceptions and Object Lifetime

Chapter// Better.6 - Interfaces and Collections

Chaptertry

7

- Callback Interfaces, Delegates, and Events

Chapter{

8

- Advanced C# Type Construction Techniques

for(int i = 0; i < 10; i++)

Part Three - Programming with .NET Assemblies

buddha.SpeedUp(10);

Chapter 9 - Understanding .NET Assemblies

}

Chapter 10 - Processes, AppDomains, Contexts, and Threads catch(CarIsDeadException e)

Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming

{...}

Part Four - Leveraging the .NET Libraries

catch(ArgumentOutOfRangeException e)

Chapter 12 - Object Serialization and the .NET Remoting Layer

{...}

Chapter 13 - Building a Better Window (Introducing Windows Forms) catch(Exception e) // This will handle any other exception.

Chapter 14 - A Better Painting Framework (GDI+)

{...}

Chapter 15 - Programming with Windows Forms Controls

Chapter 16 - The System.IO Namespace

Again, notice how this catch block explicitly specifies the exception type it is willing to catch. Given that you

Chapter 17 - Data Access with ADO.NET

construct your final catch logic to handle System.Exception, you write an exception handling routine that can (in

Part Five - Web Applications and XML Web Services

effect) work with any type deriving from System.Exception (given that all types defined in a catch block must de

Chapter 18 - ASP.NET Web Pages and Web Controls

from this base class).

Chapter 19 - ASP.NET Web Applications

Chapter 20 - XML Web Services

IndexGeneric Catch Statements

List of Figures

C# (as well as numerous other languages targeting the .NET platform) also supports a generic catch block tha

List of Tables

does not explicitly define the type of exception. Thus, you could implement a catch block as follows:

// I handle any possible error thrown from a try block.

catch

{

Console.WriteLine("Something bad happened...");

}

Obviously, this is not the most descriptive manner in which to handle runtime exceptions, given that you have no way to obtain meaningful information about the error that occurred (such as the method name, call stack, or custom message). Nevertheless, C# does allow for such a construct.

Rethrowing Exceptions

Also, beware that it is permissible to "rethrow" an error up the call stack to the previous caller. To do so, simply

C# and the .NET Platform, Second Edition

make use of the "throw" keyword within a catch block. This passes the exception up the chain of calling logic:

 

by Andrew Troelsen

ISBN:1590590554

try

Apress © 2003 (1200 pages)

 

This comprehensive text starts with a brief overview of the

{

C# language and then quickly moves to key technical and

// Speed up car logic...

architectural issues for .NET developers.

}

catch(CarIsDeadException e)

Table{ of Contents

// Do any partial processing of this error and pass the buck.

C# and the .NET Platform, Second Edition

// Here, we are rethrowing the CarIsDeadException type.

Introduction

// HOWEVER, you are also free to throw a different exception if need be.

Part One - Introducing C# and the .NET Platform

throw e;

Chapter 1 - The Philosophy of .NET

Chapter}

2

- Building C# Applications

Part Two - The C# Programming Language

Chapter 3

- C# Language Fundamentals

Chapter 4

- Object-Oriented Programming with C#

Chapter 5

- Exceptions and Object Lifetime

Chapter 6

- Interfaces and Collections

Chapter 7

- Callback Interfaces, Delegates, and Events

Chapter 8

- Advanced C# Type Construction Techniques

Part Three - Programming with .NET Assemblies

Chapter 9 - Understanding .NET Assemblies

Chapter 10 - Processes, AppDomains, Contexts, and Threads

Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming

Part Four - Leveraging the .NET Libraries

Chapter 12 - Object Serialization and the .NET Remoting Layer

Chapter 13 - Building a Better Window (Introducing Windows Forms)

Chapter 14 - A Better Painting Framework (GDI+)

Chapter 15 - Programming with Windows Forms Controls

Chapter 16 - The System.IO Namespace

Chapter 17 - Data Access with ADO.NET

Part Five - Web Applications and XML Web Services

Chapter 18 - ASP.NET Web Pages and Web Controls

Chapter 19 - ASP.NET Web Applications

Chapter 20 - XML Web Services

Index

List of Figures

List of Tables

The FinallyC#Blockand the .NET Platform, Second Edition

by Andrew Troelsen

ISBN:1590590554

Your try/catch logic may also be augmented with an optional finally block. The idea behind a finally block

Apress © 2003 (1200 pages)

is to ensure that a block of code will always execute, even if an exception (of any type) interferes with the

This comprehensive text starts with a brief overview of the

normal flow of executionC# language. For example,and then quicklyassumemovesyou wishto keytotechnicalalways powerand down the car's radio before exiting Main(), regardlessarchitecturalof anyissuespossiblefor .NETexception:developers.

// Provide a manner to clean up.

Table of Contents

public static int Main(string[] args)

C# and the .NET Platform, Second Edition

{

Introduction

...

Part One - Introducing C# and the .NET Platform

// Try to rev the engine hard!

Chapter 1 - The Philosophy of .NET

try

Chapter 2 - Building C# Applications

{

Part Two - The C# Programming Language

// Speed up car logic ...

Chapter 3 - C# Language Fundamentals

}

Chapter 4 - Object-Oriented Programming with C# catch(CarIsDeadException e)

Chapter {5...- Exceptions} and Object Lifetime

Chapter catch(ArgumentOutOfRangeExceptiond6 - Interfaces Collections e)

Chapter {7...- Callback} Interfaces, Delegates, and Events

finally

Chapter 8 - Advanced C# Type Construction Techniques

{

Part Three - Programming with .NET Assemblies

// This will always occur. Exception or not.

Chapter 9 - Understanding .NET Assemblies

buddha.CrankTunes(false);

Chapter 10 - Processes, AppDomains, Contexts, and Threads

}

Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming

return 0;

Part Four - Leveraging the .NET Libraries

}

Chapter 12 - Object Serialization and the .NET Remoting Layer Chapter 13 - Building a Better Window (Introducing Windows Forms)

Chapter 14 - A Better Painting Framework (GDI+)

If you did include a finally block, the radio would not be turned off if an exception is caught (which may or

Chapter 15 - Programming with Windows Forms Controls

may not be problematic). In a more real-world scenario, if you need to clean up any allocated memory,

Chaptcloser 16 - The System.IO Namespace

down a file, or detach from a data source (or whatever), you must add that code within a finally block Chapterto ensure17 proper- Data Accesscleanupwith. ToADOthis.NETend, it is important to realize that the code contained within a finally

PartblockFiveexecutes- Web Applicationsall the time,andevenXMLif theWeblogicServiceswithin your try clause does not generate an exception. This is

Chaespeciallyter 18 -helpfulASP.NETif aWebgivenPagesexceptionand WebrequiresControlsthe termination of the current application.

Chapter 19 - ASP.NET Web Applications

Chapter 20 - XML Web Services

Index

List of Figures

List of Tables

The Last ChanceC# and theException.NET Platform, Second Edition

by Andrew Troelsen

ISBN:1590590554

Unlike ad hoc error handling techniques, .NET exceptions cannot be ignored. One obvious question that

Apress © 2003 (1200 pages)

may be on your mind is what would happen if you do not handle an exception thrown your direction. For

This comprehensive text starts with a brief overview of the

example, assumeC#thatlanguagethe logicandinthenMain()quicklythat increasesmoves to keythe technicalspeed ofandthe Car object has no error handling logic. The result ofarchitecturalignoring theissugenerateds for .NETerrordeveloperswould be. highly obstructive to the end user of your application, as the following "last chance exception" dialog box is displayed (Figure 5-5).

Table of Contents

C# and

Part

Chapter

Chapter

Part

Chapter

Chapter

Chapter

Chapter

Chapter

Chapter

Part

Chapter

 

Chapter

Threads

Chapter

-Based Programming

Part

 

Chapter

Layer

Chapter 13 - Building a Better Window (Introduci

g Windows Forms)

Figure 5-5: You have just entered no-man's land.

Chapter 14 - A Better Painting Framework (GDI+)

Now that you see the inherent goodness of catching an exception programmatically, you may wonder what

Chapter 15 - Programming with Windows Forms Controls

to do with the exception once you have trapped it. Again, this is a design issue based on your current

Chapter 16 - The System.IO Namespace

project. In your trivial Car example, you simply dumped your custom message and call stack to the

Chapter 17 - Data Access with ADO.NET

console. A more realistic scenario may include freeing up acquired resources or writing to a log file. The

Part Five - Web Applications and XML Web Services

exception-handling schema is simply a pattern to follow when sending, receiving, and processing runtime

Chapter 18

- ASP.NET Web Pages and Web Controls

anomalies. How you do so is largely up to you.

Chapter 19

- ASP.NET Web Applications

Chapter 20

- XML Web Services

SOURCE

The CustomException project is included under the Chapter 5 subdirectory.

IndexCODE

List of Figures

List of Tables

List of Tables
List of Figures

DynamicallyC#Identifyingand the .NET Platform,ApplicationSecond Edition- and System-Level Exceptions

by Andrew Troelsen

ISBN:1590590554

In the previous example, you saw how to handle each exception by its specific class name. As an

Apress © 2003 (1200 pages)

illustrative alternative, assume you wish to generalize your catch blocks in such a way that all application-

This comprehensive text starts with a brief overview of the level exceptions areC# languagehandled apartand henfromquicklypossiblemovessystemto key-levelt chnicalexceptions:and

architectural issues for .NET developers.

// This time, make things a bit more general.

try

Table of Contents

{

C# and the .NET Platform, Second Edition for(int i = 0; i < 10; i++)

Introduction

buddha.SpeedUp(10);

Part One - Introducing C# and the .NET Platform

}

Chapter 1 - The Philosophy of .NET

Chapter 2 - Building C# Applications

// Any type derived from System.ApplicationException

Part Two - The C# Programming Language

// handled here.

Chapter 3 - C# Language Fundamentals

catch(ApplicationException e)

Chapter 4 - Object-Oriented Programming with C#

{

Chapter Console5 - Exc ptions.WriteLine("Caughtand Object Lifetime an app exception!");

Chapter Console6 - Interfaces.WriteLine("Method:and Collections {0}", e.TargetSite);

Chapter Console7 - Ca lback.WriteLine("Message:In erfaces, Del gates, and{0}",Events e.Message);

}

Chapter 8 - Advanced C# Type Construction Techniques

// Any type derived from System.SystemException

Part Three - Programming with .NET Assemblies

// handled here.

Chapter 9 - Understanding .NET Assemblies

catch(SystemException e)

Chapter 10 - Processes, AppDomains, Contexts, and Threads

{

Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming

Console.WriteLine("Caught a system-level exception");

Part Four - Leveraging the .NET Libraries

Console.WriteLine("Method: {0}", e.TargetSite);

Chapter 12 - Object Serialization and the .NET Remoting Layer

Console.WriteLine("Message: {0}", e.Message);

Chapter 13 - Building a Better Window (Introducing Windows Forms)

}

Chapter 14 - A Better Painting Framework (GDI+) Chapter 15 - Programming with Windows Forms Controls

Chapter 16 - The System.IO Namespace

Although the ability to discover at runtime the underlying source of an exception might sound intriguing, Chapteryou really17 -gainDatanothingAccessbywithdoingADOso.NET. Sadly, if you spend time digging through the .NET base class libraries,

PartyouFivewill find- WebthatApplicationssome baseandclassXMLlibraryWeb Servicesmethods that should ideally throw a type derived from

ChapSystemr 18.SystemException- ASP.NET Web Pagesare inandfactWderivedb Contfromls System.ApplicationException or even the more generic

ChapSystemr 19.Exception!- ASP.NET Web Applications

Chapter 20 - XML Web Services

Thus, although the proposed idea issued by Microsoft was noble, you cannot always use the previous

Index

technique to universally determine the source of the exception. In your applications, you will do well to simply handle each possible exception on a name-by-name basis. However, if you are building a custom exception class, best practice dictates deriving directly from System.ApplicationException.

Chapter 1 - The Philosophy of .NET
Part One - Introducing C# and the .NET Platform

DebuggingC#Systemand the .NExceptionsT Platform, SecondUsingEditionVS .NET

by Andrew Troelsen

ISBN:1590590554

Visual Studio .NET provides a number of helpful tools that you can use to debug the exceptions that may

Apress © 2003 (1200 pages)

be thrown by a given member during the development cycle. By default, when an exception is caught

This comprehensive text starts with a brief overview of the

during a debuggingC#session,languagetheandIDEthenwillquicklynot automaticallymoves to keystopechnicalat theandoffending line of code.

architectural issues for .NET developers.

To illustrate this default behavior, begin to debug your current CustomExceptions project without setting any breakpoints. You will find that the only visible display of the CarIsDeadException is the information

Tableprintedof Ctontthentsconsole (via your catch block), which disappears so quickly you cannot see the error. Of C#course,and theyou.NETarePlatform,free to setSecondany numberEdition of manual breakpoints by hand; however, there is a better way.

Introduction

VS .NET may be configured to automatically break whenever an exception occurs, without requiring you to set dozens of manual breakpoints at various catch blocks. When you wish to enable such support, begin

by launching the Exceptions dialog box, using the Debug | Exceptions menu selection (Figure 5-6).

Chapter 2 - Building C# Applications

Part Two - The C# Programming Language

Chapter

Chapter

Chapter

Chapter

Chapter

Chapter

Part

Chapter

 

Chapter

 

Chapter

Programming

Part

 

Chapter

 

Chapter

Forms)

Chapter

 

Chapter

 

Chapter

 

Chapter

 

Part

 

Chapter

 

Chapter

 

Chapter

IndexFigure 5-6: Preparing to enable VS .NET exception handling

List of Figures

ListAsofyouTablescan see, VS .NET is able to interact with various types of exceptions; the only category of interest is the common language runtime exceptions. If you open up the CLR Exceptions node, you will find a list of all of the System.Exception-derived types that Visual Studio .NET is aware of. For example, if you open up the System node, you will find a list of all exception types listed in this namespace (Figure 5-7).

ISBN:1590590554

overview of the

technical and

Table

C# and

Part

Chapter

Chapter

Part

Chapter

Chapter

Chapter

Chapter

Chapter

Chapter

Figure 5-7: The CLR exception set

Part Three - Programming with .NET Assemblies

Chapter 9 - Understanding .NET Assemblies

To enable automatic breaking for a specific exception, simply select the exceptions of interest. For

Chapter 10 - Processes, AppDomains, Contexts, and Threads

example, to instruct VS .NET to automatically break when an ArgumentOutOfRange exception occurs,

Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming check the "Break into the debugger" option (Figure 5-8).

Part Four - Leveraging the .NET Libraries

Chapter 12 - Object Serialization and the .NET Remoting Layer

Chapter

Forms)

Chapter

Chapter

Chapter

Chapter

Part

Chapter

Chapter

Chapter

Index

List of

List of

Figure 5-8: Specifying VS .NET exception support for a given exception

Handling Custom Exceptions Using VS .NET

In addition to handling system-level exceptions, you are also able to configure Visual Studio .NET to

handle your custom application exceptions (such as the CarIsDeadException). To do so, first select the

C# and the .NET Platform, Second Edition

CLR Exceptions node and click the Add button. At this point, type in the fully qualified name of your custom

by Andrew Troelsen ISBN:1590590554 exception type (Figure 5-9).

Apress © 2003 (1200 pages)

This comprehensive text starts with a brief overview of the moves to key technical and

developers.

Table

C# andFigurethe .NET5-9:Platform,EnablingSecondyour customEditionapplication exceptions via VS .NET

Introduction

Part One - Introducing C# and the .NET Platform

At this point you are able to configure the custom exception as if it were a standard exception (Figure 5-

Chapter 1 - The Philosophy of .NET

10).

Chapter 2 - Building C# Applications

Part Two - The C# Programming Language

Chapter

Chapter

Chapter

Chapter

Chapter

Chapter

Part

Chapter

 

Chapter

Threads

Chapter

-Based Programming

Part

 

Chapter

Layer

Chapter

Windows Forms)

Chapter

 

Chapter

 

Chapter

 

Chapter

 

Part FiveFigure- Web5-10:ApplicatioHandlings andyourXMLcustomWebapplicationServices exceptions via VS .NET

Chapter 18 - ASP.NET Web Pages and Web Controls

With this, you are now able to debug your application, and automatically step into the debugger when a

Chapter 19 - ASP.NET Web Applications

given exception is raised.

Chapter 20 - XML Web Services

Index

So then, this wraps up the first topic of the chapter. As you read over the remainder of this text, you will be

List of Figures

introduced to numerous other system-level exceptions. Next up, we will turn our attention to the topic of

List of Tables object lifetime.

Note To make the code examples used in this text as clean as possible, I will not catch every possible exception that may be thrown by a CLR type. Do be aware that your production-level projects should, of course, make liberal use of try/catch/finally blocks.

UnderstandingC# andObjectthe .NET Platform,LifetimeS cond Edition

by Andrew Troelsen

ISBN:1590590554

To close this chapter, we will switch topics completely and address garbage collection. Recall that unlike

Apress © 2003 (1200 pages)

C++, C# programmers (and .NET programmers in general) never directly deallocate an object from

This comprehensive text starts with a brief overview of the

memory (thereforeC#therelanguageis noand"delete"then quicklykeywordmovesin thetoC#keylanguage)technical.andRather, .NET objects are allocated onto a region of memoryarchitecturaltermedissuestheformanaged.NET develoheapers, where. they will be automatically deallocated by the runtime at "some time in the future."

TableAs youf Contentsare building your C# applications, you are correct to assume that the managed heap will take care C#of anditselfthewithout.NET Platform,your directSecondinterventionEdition. In fact, the golden rule of .NET memory management is simple.

Introduction

Part One - Introducing C# and the .NET Platform

Rule: The Zen of .NET memory management says this: Allocate an object onto the managed heap

Chapter 1 - The Philosophy of .NET

using the "new" keyword and forget about it.

Chapter 2 - Building C# Applications

PartOnceTwo"new- The-ed,"C#theProgrammingCLR removesLanguagethe object when it is no longer needed. Next question: How does the Chapterruntime3determine- C# Languagewhen anFundamentalsobject is "no longer needed"? The short (i.e., incomplete) answer is that the

runtime removes an object from the heap when it is unreachable by the current application. To illustrate,

Chapter 4 - Object-Oriented Programming with C#

assume you have a new application that makes use of the Car type as follows:

Chapter 5 - Exceptions and Object Lifetime

Chapter 6 - Interfaces and Collections

Chapter// Create7 - CallbacklocalInterfaces,Car objectDel ga es,. and Events

public static int Main(string[] args)

Chapter 8 - Advanced C# Type Construction Techniques

{

Part Three - Programming with .NET Assemblies

// Place an object onto the managed heap.

Chapter 9 - Understanding .NET Assemblies

Car c = new Car("Viper", 200, 100);

Chapter 10 - Processes, AppDomains, Contexts, and Threads

...

Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming

} // If c is the only reference to the Car object,

Part Four - Leveraging the .NET Libraries

// itmaybe destroyed when Main() exits.

Chapter 12 - Object Serialization and the .NET Remoting Layer Chapter 13 - Building a Better Window (Introducing Windows Forms)

Chapter 14 - A Better Painting Framework (GDI+)

Notice that the Car variable (c) has been created within the scope of Main(). Thus, once the application

Chapter 15 - Programming with Windows Forms Controls

shuts down, this reference is no longer valid, and therefore is a candidate for garbage collection.

ChaptUnderstand,r 16 - Thowever,System.IO Namespace

that you cannot guarantee that this object will be reclaimed from memory when ChapterMain() has17 -completedData Access. AllwithyouADOcan.NETassume at this point in the game is that when the CLR performs the

PartnextFivegarbage- Webcollection,Applications"c"andis readyXML Webto beServicesdestroyed.

Chapter 18 - ASP.NET Web Pages and Web Controls

Chapter 19 - ASP.NET Web Applications

Chapter 20 - XML Web Services

Index

List of Figures

List of Tables

The CIL of "new"C# and the .NET Platform, Second Edition

by Andrew Troelsen

ISBN:1590590554

Under the hood, when the C# compiler encounters the "new" keyword, it will emit a CIL "newobj"

Apress © 2003 (1200 pages)

instruction to the code module. Thus, if you were to open up the previous assembly using ildasm.exe, you

This comprehensive text starts with a brief overview of the would find the followingC# languageCIL: and then quickly moves to key technical and

architectural issues for .NET developers.

.method public hidebysig static int32 Main(string[] args) cil managed

{

Table of Contents

.entrypoint

C# and the .NET Platform, Second Edition

// Code size

24 (0x18)

Introduction

.maxstack 4

Part One - Introducing C# and the .NET Platform

.locals init ([0] class GC.Car c,

Chapter 1

- The Philosophy of .NET

 

 

[1] int32 CS$00000003$00000000)

Chapter 2

- Building C# Applications

IL_0000:

ldstr

"Viper"

Part Two - The C# Programming Language

IL_0005:

ldc.i4

0xc8

Chapter 3

- C# Language Fundamentals

IL_000a:

ldc.i4.s

100

Chapter 4 - Object-Oriented Programming with C#

IL_000c: newobj instance void GC.Car::.ctor

Chapter(string,5 - Exceptint32,ons and Objectint32)Lifetime

ChapterIL_0011:6 - Interfacesstlocand.0Collections

ChapterIL_0012:7 - CallbackldcInterfaces,.i4.0 Delegates, and Events

IL_0013: stloc.1

Chapter 8 - Advanced C# Type Construction Techniques

IL_0014: br.s IL_0016

Part Three - Programming with .NET Assemblies

IL_0016: ldloc.1

Chapter 9 - Understanding .NET Assemblies

IL_0017: ret

Chapter 10 - Processes, AppDomains, Contexts, and Threads

} // end of method GCApp::Main

Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming

Part Four - Leveraging the .NET Libraries

Chapter 12 - Object Serialization and the .NET Remoting Layer

Before we examine the exact rules that determine when an object is removed from the managed heap,

Chapter 13 - Building a Better Window (Introducing Windows Forms)

let's check out the role of the CIL newobj instruction in a bit more detail. First, understand that the

Chapter 14 - A Better Painting Framework (GDI+)

managed heap is more than just a raw chunk of memory accessed by the CLR. The .NET garbage

Chapter 15 - Programming with Windows Forms Controls

collector is quite a tidy housekeeper, given that it will compact empty blocks of memory (when necessary)

Chapter 16 - The System.IO Namespace

for purposes of optimization. To aid in this endeavor, the managed heap maintains a pointer (commonly Chapterreferred17to-asDatatheAccessnew objectwith ADOpointer.NET) that identifies exactly where the next object will be placed on the

PartheapFiveitself- Web. TheseApplicationsthings beinga d XMLsaid,Webthe newobjS rvicesinstruction informs the CLR to perform the following

Chaptersequence18 -ofASPevents:.NET Web Pages and Web Controls

Chapter 19 - ASP.NET Web Applications

Calculate the total amount of memory required for the object about to be allocated. As you would

Chapter 20 - XML Web Services

Indexexpect, if this object contains other internal objects (i.e., the "has-a" relationship as well as nested type

members), they are also factored into the equation. As well, the memory required for each base class

List of Figures

is also taken into account (i.e., the "is-a" relationship).

List of Tables

The CLR then examines the managed heap to ensure that there is indeed enough room to host the object to be allocated. If so, the type's constructor is called, and the caller is returned a reference to the type in memory, which just happens to be identical to the last position of the new object pointer.

Finally, before returning the reference to the caller, the CLR will advance the new object pointer to point to the next available slot on the managed heap.

This process is illustrated in Figure 5-11.

ISBN:1590590554

of the

and

Table

Figure 5-11: Reference types are allocated on the managed heap.

C# and the .NET Platform, Second Edition

Introduction

Part One - Introducing C# and the .NET Platform

Chapter 1 - The Philosophy of .NET

Chapter 2 - Building C# Applications

Part Two - The C# Programming Language

Chapter 3 - C# Language Fundamentals

Chapter 4 - Object-Oriented Programming with C#

Chapter 5 - Exceptions and Object Lifetime

Chapter 6 - Interfaces and Collections

Chapter 7 - Callback Interfaces, Delegates, and Events

Chapter 8 - Advanced C# Type Construction Techniques

Part Three - Programming with .NET Assemblies

Chapter 9 - Understanding .NET Assemblies

Chapter 10 - Processes, AppDomains, Contexts, and Threads

Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming

Part Four - Leveraging the .NET Libraries

Chapter 12 - Object Serialization and the .NET Remoting Layer Chapter 13 - Building a Better Window (Introducing Windows Forms) Chapter 14 - A Better Painting Framework (GDI+)

Chapter 15 - Programming with Windows Forms Controls

Chapter 16 - The System.IO Namespace

Chapter 17 - Data Access with ADO.NET

Part Five - Web Applications and XML Web Services

Chapter 18 - ASP.NET Web Pages and Web Controls

Chapter 19 - ASP.NET Web Applications

Chapter 20 - XML Web Services

Index

List of Figures

List of Tables

Chapter 18 - ASP.NET Web Pages and Web Controls
Part Five - Web Applications and XML Web Services
Chapter 17 - Data Access with ADO.NET

The BasicsC#ofandGarbagethe .NET Platform,CollectionSec d Edition

by Andrew Troelsen

ISBN:1590590554

As you are busy creating objects, the managed heap may eventually become full. When the newobj

Apress © 2003 (1200 pages)

instruction is being processed, if the CLR determines that the managed heap does not have sufficient

This comprehensive text starts with a brief overview of the

memory to allocateC#thelanguagerequestedand thentype,quicklyit will performmoves toakeygarbagetechnicalcollectionand in an attempt to free up memory. Thus, thearchitectnext ruleralofissuesgarbagefor .NETcollectiondevelopersis quite. simple.

Rule: If the managed heap does not have sufficient memory to allocate a new object, a garbage

Table of Contents

collection will occur.

C# and the .NET Platform, Second Edition

Introduction

Now, assuming that the CLR performs a garbage collection, we need to return to the question regarding

Part One - Introducing C# and the .NET Platform

how the runtime is able to determine an object on the heap is "no longer needed." To understand the

Chapter 1 - The Philosophy of .NET

details, you need to be aware of the notion of application roots.

Chapter 2 - Building C# Applications

PartSimplyTwoput,- Thea C#rootProgrammingis storage locationLanguagecontaining a reference to an object on the heap. Put even more Chaptersuccinctly,3 -aC#rootLanguagecan be understoodFundamentalsas a variable in your application that points to some area of memory

on the managed heap. Strictly speaking, however, a root can fall into any of the following categories:

Chapter 4 - Object-Oriented Programming with C#

Chapter 5 - Exceptions and Object Lifetime

References to global objects (while not allowed in C#, raw CIL does permit allocation of global

Chapter 6 - Interfaces and Collections objects)

Chapter 7 - Callback Interfaces, Delegates, and Events

ChapterReferences8 - Advancedto staticC#objectsType Construction Techniques

Part Three - Programming with .NET Assemblies

References to local objects within a given method

Chapter 9 - Understanding .NET Assemblies

Chapter 10 - Processes, AppDomains, Contexts, and Threads

References to object parameters passed into a method

Chapter 11 - Type Reflection, Late Binding, and Attribute-Based Programming

Part FourAny-CPULeveraregistering thethat.NETreferencesLibrariesa local object

Chapter 12 - Object Serialization and the .NET Remoting Layer

When a garbage collection occurs, the runtime will investigate all objects on the managed heap to

Chapter 13 - Building a Better Window (Introducing Windows Forms)

determine if it is still in use (aka "rooted") in the application. To do so, the CLR will build an object graph,

Chapter 14 - A Better Painting Framework (GDI+)

which represents each object on the heap that is still reachable. We will explore object graphs in more

Chapter 15 - Programming with Windows Forms Controls

detail later during our examination of object serialization (see Chapter 12). For the time being, simply

Chapter 16 - The System.IO Namespace

understand that the CLR will ensure that all related objects are accounted for before a possible garbage collection through the construction of an object graph that documents all codependencies for the current object. One nice feature of this process is the fact that the runtime will never graph the same object twice,

thus avoiding the nasty circular reference count found in classic COM programming.

Chapter 19 - ASP.NET Web Applications

ChapterNow then,20 -onceXML theW bgarbageServic scollector determines that a given root is no longer used by a given

Indexapplication, the object is marked for termination. When the entire heap has been searched for "severed

Listroots,"of Figuresthe underlying memory is reclaimed for each unreachable object. After the objects have been Lisweptt of Tablesfrom memory, the memory on the heap is compacted, which in turn will cause the CLR to modify the set of application roots to refer to the correct memory location (this is done automatically and transparently). Finally, the new object pointer is readjusted to point to the next available slot.

Note Be aware that the garbage collection process happens on a unique thread of execution (more on threading in Chapter 10).

Соседние файлы в предмете Программирование