Exceptions and Object Lifetime

Download as ppt, pdf, or txt
Download as ppt, pdf, or txt
You are on page 1of 27

Exceptions and Object Lifetime

Introduction to Errors, Bugs & Exceptions

Bugs: An error on the part of progrmmer Eg: call to NULL pointer, failed to detect allocated memory, then it causes a bug Error: Errors are caused by end user of the application instead of those who created it. Eg: String entering on numerical field Exception: An exception is a condition i.e. caused by a run-time error in the pgm. Eg: dividing an integer by zero, it creates an exception object & throws it

Contd..

.NET base class libraries define exceptions such as, OutOfMemoryException, IndexOutOfRangeException, FileNotFoundException, ArgumentOutOfRangeException, DivideByZeroException, etc

Disadvantages of Traditional Methods

Code that depends on return value must provide additional error parameters or call other functions (e.g. Win32 API) Returning error code must be handled properly Error codes are difficult to extend and update. The entire source code must be updated for any new error codes C# uses rich Exception object which contains info about failure condition

Role of .NET Exception Handling

Code that uses exceptions are clearer and more robust than other methods .NET provides a standard technique to send and trap runtime errors: Structured Exception Handling (SHE) The developers have a unified approach to error handling Another use is that rather than receiving a cryptic numerical value that identifies the problem at hand.

The Atoms of .NeT Exception Handling

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 exceptionready method


A block of code that will process or catch the exception

Contd..

The CLR supports an exception handling model based on the concepts of exception objects and protected blocks of code The runtime creates an object to represent an exception when it occurs. You can also create your own exception classes by deriving classes from the appropriate base exception Each language uses a form of try/catch/finally structured exception handling

Contd..

To catch an exception the try-catch block must be used A try block is a section of the code that looks for an exception When an exception is raised, or thrown, within a try block, an exception object is created and a search begins in the catch block When an exception occurs within that scope, the control goes to the appropriate catch block (handler) If no exception occurs, obviously the catch block is never executed After the catch block code is executed the rest of the code in the program continues (is it OK?) Catch block can also rethrow the exception

System.Exception Base Class

Most of the memebers defined by System.Exception are read-only


Property Meaning
URL to a help file

HelpLink

InnerException
Message Source StackTrace TargetSite

details of previous exceptions that caused the current exception


returns the text describing the error name of the assembly that threw the exception sequence of calls that triggered the exception returns the MethodBase type

throw statement

The throw statement is used to signal the occurrence of an anomalous situation /exception and to send the error object back to the caller (raising an exception)

throw [expression];
expression is an exception object Usually the throw statement is used with try-catch or try-finally statements. When an exception is thrown, the program looks for the catch statement that handles this

Example (throw)
using System; public class ThrowTest { public static void Main() Output: { The following exception occurs: string s = null; System.ArgumentNullException if (s == null) { throw(new ArgumentNullException()); } // not executed Console.Write("The string s is null"); } }

Example (try - catch)


using System; class AddInts { static void Main(string[] args) { int a, b; int c, d = 0; Console.Write("Enter the first number (a): "); a = System.Int32.Parse(Console.ReadLine()); Console.Write("Enter the second number (b): "); b = System.Int32.Parse(Console.ReadLine()); c = a + b;

try { d = a / b; } catch(Exception e) { Console.WriteLine("Method: {0}", e.TargetSite);


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

Console.WriteLine("Source: {0}", e.Source); return; } Console.WriteLine("a + b = {0}", c); Console.WriteLine("a / b = {0}", d); }

}
Enter the first number (a): 28 Enter the second number (b): 0 Method: Void Main(System.String[]) //which method threw the exception Message: Attempted to divide by zero. Source: AddInts

TargetSite Property
System.Exception.TargetSite allows to determine details about the method that threw a given exception. It display the return value, name, & parameters of the method Output: Eg: static void Main(string[ ] args) Member name: void SpeedUp(Int32) { . Member type: method Class defining member: SimpleException.Car catch (Exception e) { ConsoleWriteLine(Member name:{0},e.TargetSite); ConsoleWriteLine (Member Type :{0}, e.TargetSite.MemberType); ConsoleWriteLine (Class defining member:{0}, e.TargetSite.DeclaringType); }}

StackTrace Property
StackTrace: Displays sequence of calls that resulted in throwing the exception. We can follow the flow of the error's origin It automatically established at the time the exception is created Output: Eg: static void Main(string[ ] args) Stack: at
{ . catch(Exception e) { }
simpleException.Car.SpeedUp(Int32 delta) in c:\myapp\exceptions\car.cs: line 65 at Exceptions.App.Main() in c:\myapps\exceptions\app.cs: line 21

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

HelpLink Property

HelpLink: Point to the user to a specific URL or standard windows help file that contains more detailed information. By default, the value managed by the HelpLink property is an empty string Fill the interesting value, before throwing the System.Exception type
{ // create a new Exception object, passing a string Exception myException = new Exception("myException"); // set the HelpLink myException.HelpLink = "See the Readme.txt file"; // or myException.HelpLink= http://www.carRUs.com ; // throw the Exception object throw myException; } catch (Exception e) { Console.WriteLine("HelpLink = " + e.HelpLink); } Output:
HelpLInk = See the Readme.txt file

Eg: try

Data Property

Data: returns an object implementing an interface named IDictionary, defined in the System.Collection namespace Dictionary collection allows to create a set of values that are retrieves using a specific key value
{ // create a new Exception object, passing a string Exception myException = new Exception("myException"); myException.Data.Add = (TimeStamp, string.Format(The car exploded at {0}, DateTime.Now)); myException.Data.Add= (cause, You have a lead foot); throw myException; } catch (Exception e) { if (e.Data!=null) { foreach (DictionaryEntry de in e.Data) Console.WriteLine({0}:{1} = " , de.key, de.value); } Output:
TimeStamp: The car exploded at 10/25/2010 9:26:58 PM Cause: You have a lead foot

Eg: try

System-Level Exceptions (System.SystemException)


Exceptions thrown by the CLR are called system exceptions These exceptions are regarded as nonrecoverable, fatal errors It derive directly from a base class System.SystemExceptions, which in turn derived from System.Exception

Public class SystemException:Exception { // various constructors public SysyemException(); public SysyemException(string message); }

It does not add any other functionality beyond a set of constructors When an exception type derives from System.SysteException, we are able to determine that the .NET runtime is the entity that has thrown the exception, rather than the code base execution application

Application-Level Exceptions (System.ApplicationException)

It derive directly from a base class System.ApplicationExceptions, which in turn derived from System.Exception

Public class ApplicationException:Exception { // various constructors public ApplicationException(); public ApplicationException(string message); }

It does not add any other functionality beyond a set of constructors Only purpose is to identify the source of the (nonfatal) error When an exception type derives from System.ApplicationException, we can assume the exception was raised by the code base of the executing application, rather than .NET base class libraries.

Building Custom Exceptions

Though the System level exceptions are useful, sometimes it is necessary to build user defined exceptions Define a new user defined class derived from System.Exception You may override any virtual members defined in the parent class

Example
public class CarIsDeadException:System.Exception { public string CarName; public CarIsDeadException() { } public CarIsDeadException(string CarName) { this.CarName=CarName; } } public void Speedup(int Delta) { try { if(CarIsDead) { throw new CarIsDeadException(First); } } catch(CarIsDeasException e) { Console.WriteLine(Message {0}:, e.Message); } }

Multiple Exceptions

The code in the try block may trigger more than one exception. Under these circumstances you can have more than one catch block Exception will be processed by the nearest available catch block Ex: public void Speedup(int delta) { if(delta<0) throw new ArgumentOutOfRangeException(must > 0); if(CarIsDead) throw new CarIsDeadException(it has farm!); . }

Multiple Exceptions
try { for (int i=0;i<10;i++) b.Speedup(10); } catch(CarIsDeadException e) { CW(Method:{0},e.TargetSite); CW(Message:{0},e.Message); } catch(ArgumentOutOfRangeException e) { CW(Method:{0}, e.TargetSite); CW(Message:{0},e.Message); }

Multiple Exceptions
(Below example is wrong!) Ex: try { }
catch (Exception e) {} catch (CarIsDeadException e) {} catch (ArgumentOutOfRangeException e) {}

Catch blocks are structured such that the very first catch is the most specific and final catch is the most general (i.e. System.Exception)

Other types of Exception Handling

Generic catch try {} catch {} Rethrowing Exceptions : use the throw keyword within a catch block try {} catch (NegNumException e) { // handle the error & call stack to the previous caller throw e; }

Contd
Finally Block - The optional finally block will get executed always - Useful for cleaning up process or close the database files - It may be added immediately after the try block or after the last catch block

try { .} finally {..}

try {} catch(..)

{.}
catch () { . } finally {}

Example
using system; class Error1 { public static void Main() { int[ ] a = {5,10}; int b=5; try { int x = a[2] / b a[1]; } catch(AirthmeticException e) { CW(Division by zero ); } catch (IndexOutOfRangeException e) { CW(Array index error); finally { int y = a[1]/a[0]; CW (y = , +y); } }

Output :
Array index error Y=2

You might also like