.comment-link {margin-left:.6em;}

Tuesday, February 22, 2005

 

Why Do We have Different exception Classes ?

i still get the same question frequently . why do we have more than 1 exception class ?

isnt it enough to write code like this :

try {

// protected Code}

catch (Exception ex)

{ // switch (ex) and handle each exception separately }

the exception class will catch all kind of exceptions . and we can internally handle each exception separately .

no , this is not enough , why ?

let's take this sample

try {System.IO.File.Delete("z:\filenotfound.txt");}

catch (exception ex) { //what can we do here if we need to know the name of the file which is not found ?}

so there must be some "Data" about the kind of exception taking place , in our case the name of the file .so that's why we have FileNotFoundException . so it is much more convinient to write something like this :

try {System.IO.File.Delete("z:\filenotfound.txt");}

catch (FileNotFoundException ex) { Console.Writeline(ex.FileName);}

another example will be the ArgumentOutOfRangeException : we need to know the original value of the argument which is out of range .

try {//cause some argument out of range error;}

catch (ArgumentOutOfRangeException ex) { Console.Writeline(ex.ActualValue);}

VS 2005 :

so what is new in 2005 . in VS 2005 we have all the exception classes having a new property which is : Data , that contains all the information available about this error . it looks like the event model of .NET where Microsoft encapsulates all the information about any event in the second parameter of the event "EventArgs e". so now we have "Exception.Data"


Comments: Post a Comment



<< Home

This page is powered by Blogger. Isn't yours?