Chapter 5: Exception Handling and Object Lifetime
lecture
in color
contents of chapter5.txt:
Chapter 5: Exceptions and Object Lifetime
Two goals:
- How to handle run time anomalies in your code through the use of structured exception handling.
- Understand and control the process of object lifetime management by the CLR.
Problems with Code come in three flavors: Bugs, Errors, and Exceptions.
- Bugs: Include programming mistakes that range from typos, to pointer mistakes, to invalid allocations and object types, to undeleted memory objects. All of these can be generally categorized as programmer errors.
- Errors: These include problems in the application generated from unexpected usage of the application, from the user or data input. This includes improperly formatted string input, lack of input, or excessive input which can result in problems similar to bugs.
- Exceptions: Are generally considered runtime anomalies that are usually unforeseen, or unable to be prevented. Examples include corrupted data files, unavailable databases, or interfacing with unknown objects. The thread of commonality is that the programmer is not able to control if or when these problems occur, only the handling of them when they do.
History of Exception Handling:
- Exception Handling was historically application, language, and platform specific.
- This created a large problem understanding the different error codes that were given for different applications.
- .Net provides one technique to combine and standardize all these exception handling techniques.
The .NET Exception Handling contains for parts:
- A type that represents the details of the exceptional circumstance
- A method that throws the exception to the caller
- A block of code that will invoke the exception-ready method.
- A block of code that will process (or
catch) the exception (if it occurs)
- There are 4 keywords to that control exception handling:
try, catch, throw, & finally
Exceptions are derived form the System.Exception base class. The core members include:
HelpLink: This property returns a URL to a help file describing the error in detail.
Message: The read-only property containing a textual message of the error.
Source: The name of the assembly that threw the exception
StackTrace: A string that identifies the sequence of calls that triggered the exception.
TargetSite:A MethodBase type that describes detail about the method that threw the exception.
InnerException: A read only property that can be used to obtain info about the previous exceptions that have caused the current exception to occur.
Throwing an exception:
Public void Speedup(int delta){
if(carIsDead) throw new Exception(“This car is already dead…”);
else{}
}
- An exception is generally thrown in programs when items such as lack of memory, unavailable resource, or corrupted data occur, where the program may not be able to recover completely.
Catching Exceptions:
- The code below is an example of a try/catch block within a class.
public class ExceptionApp{
public static int Main(string[] args){
// Make a simple car.
Console.WriteLine("***** Creating a car and stepping on it *****");
Car buddha = new Car("Buddha", 100, 20);
buddha.CrankTunes(true);
// Try to rev the engine hard!
try{
for(int i = 0; i < 10; i++){buddha.SpeedUp(10);}
}
catch(Exception e){
Console.WriteLine("\n*** Error! ***");
Console.WriteLine("Class defining member: {0}",
e.TargetSite.DeclaringType);
Console.WriteLine("Member type: {0}", e.TargetSite.MemberType);
Console.WriteLine("Member name: {0}", e.TargetSite);
Console.WriteLine("Message: {0}", e.Message);
Console.WriteLine("Source: {0}", e.Source);
Console.WriteLine("Stack: {0}", e.StackTrace);
Console.WriteLine("Help Link: {0}", e.HelpLink);
}
Console.WriteLine("\n***** Out of exception logic *****");
return 0;
}
}
- A try block is a section of code that may experience an exception in the execution scope. If an exception is generated, then control is transferred to the corresponding catch block. If the try block does not generate an exception, then the catch block is skipped, and the code is resumed after the catch block.
- The TargetSite property returns a strongly typed System.Reflection.MethodBase class. This abstract type can include more information by including it’s subclasses as found with TargetSite.DeclaringType, and TargetSite.MemberType found above, which provide the fully qualified name of the of calls that threw the error, and the type of member, respectively.
- StackTrace Property
- The StrackTrace property allows for the determination of the series of calls that resulted in the exception. This is called by:
catch(Exception e){
…
Console.WriteLine(“Stack: {0}”, e.StackTrace);
}
- An example of what this would print is:
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:lin 21
- The System.String returned from StackTrace documents the sequence of calls that resulted in the throwing of this exception. The order is bottom up, where the first offender is listed on the bottom, to the most recent on the top.
- HelpLink Property
- CLR System-Level
Important Note: It is not required to handle every exception, as found in Java, as .NET institutes a “last chance exception” to continue execution of uncaught exceptions.
- Custom Application-Level Exceptions (System.ApplicationException)
- .NET allows for customization of base class error messages within proprietary applications run through .NET.
- Building Custom Exception
- Handling Multiple Exceptions
- Multiple exceptions are handled using multiple catch blocks ordered from top to bottom, and should be ordered from most specific to least specific. Using (Exception e) followed by other blocks with generate compile errors.
- Generic Catch Statements: C# supports generic catch blocks that are nothing more then a Console.WriteLine statement if desired.
- Rethrowing Exceptions
- The Finally Block
- The keyword
finally allows for code to be executed whether or not an exception occurs. This can be helpful to prevent premature termination of the application if so desired.
- Last Chance Exception
I=============================================================================================================================
I=============================================================================================================================
Object Lifetime
- Garbage collection is automatic is .NET with C#, unlike C++ or C.
- .Net Objects are allocated onto the
managed heap, where they are automatically deallocated by the runtime at “some time in the future”
- Memory allocations should be made using the “new” keyword.
- The CLR removes the object when it is unreachable by the current application.
public static int Main(string[] args){
Car c = new Car(“Viper”, 200, 100);
}
// If c is the only reference to the Car object, it |MAY| be destroyed when Main() exits.
- Garbage Collection
- References to global objects
- References to static objects
- References to local objects within a given method
- References to object parameters passed into a method
- Any CPU register that references a local object.
Finalizing (explicit memory deallocation for unmanaged resources through System.Object.Finalize())
Class FinalizedCar{
~FinalizedCar(){Console.WriteLine(“=> Finalizing car…”); }
}
- This creates an override for the virtual System.Object.Finalize() method, and is reflected in the CIL code.
- When an object is placed on the heap, it is determined if it supports the Finalize() method.
- The performance penalty can be avoided by not calling the Finalize() method, and replacing it with an ad hoc destruction method all objects implement.
The IDisposable Interface
public Car : IDisposable{
// custom method that the user must call manually
public void Dispose(){
// Clean up the internal unmanaged resources here
}
}
public static int Main(string[] args){
car c1 = new Car(“F1”, 400, 10);
c1.Dispose();
return 0;
}// c1 is still on the heap and maybe collected at this point
Garbage Collection Optimizations
- The CLR utilizes the concept of
generations. This means that the older an object is, the more likely it is to stick around in memory, and the newer it is, the less likely it is to stay in memory. There are three generations levels defined in .NET version 1.1:
Generation 0: Identifies a newly allocated object that has never been marked for collection
Generation 1: Identifies an object that has survived a garbage collection (marked, but not removed)
Generation 2: Identifies an object that has survived multiple garbage collections sweeps.
- The garbage collected sweeps the first generation, removing deletion marked items. If the heap requirements are met, promotes all G0 objects to G1. If not, then a sweep of G1 occurs, followed by a sweep of G2 if necessary.
- The garbage collector supports direct interaction by use of the System.GC type. This allows for the following methods to be called:
- Collect(), GetGeneration(), MaxGeneration, ReRegisterForFinalize(), SuppressFinalize(), & GetTotalMemory()
Note: SuppressFinalize() can be called in the Dispose() method after manual cleanup, to prevent calls to Finalize().
Forcing a Garbage Collection
- To Force a garbage collection a call to GC.Collect() can be made, uses include long running bacgroung processes that use large memory resources for short amounts of time, and then are idle for longer amounts of time. If a call to GC.Collect() is made, it is recommended that it is followed by GC.WaitForPendingFinalizer(s() so that the current thread can be suspended until the garbage collection is done, to prevent invoking methods on a type that is currently being destroyed.
lecture
in color
/comp/194NET/notes/chapter5.php3
downloaded on Nov-23-2009 05:29:06 AM,
was last modified on Feb-24-2004 08:32:13 AM.
All lecture note content is copyright 2004 by the Tufts .NET Study Group