How to do it...

  1. Create a class called Chapter3 (if you have not done so already) that contains two methods. One method reads the XML file, and the second method logs any exception errors:
        public void ReadXMLFile(string fileName)
{
try
{
bool blnReadFileFlag = true;
if (blnReadFileFlag)
{
File.ReadAllLines(fileName);
}
}
catch (Exception ex)
{
Log(ex);
throw;
}
}

private void Log(Exception e)
{
/* Log the error */
}
  1. In the console application, add the following code to call the ReadXMLFile method, passing it the filename to read:
Chapter3 ch3 = new Chapter3();
string File = @"c:tempXmlFile.xml";
ch3.ReadXMLFile(File);
  1. Running the application will generate an error (assuming that you actually don't have a file called XMLFile.xml in your temp folder. Visual Studio will break on the throw statement:
  1. The Log(ex) method has logged the exception, but have a look at the Watch1 window. We have no idea what the value of blnReadFileFlag is. When an exception is caught, the stack is unwound (adding overhead to your code) to whatever the actual catch block is. Therefore, the state of the stack before the exception happened is lost. 
  1. Modify your ReadXMLFile and Log methods as follows to include an exception filter:
        public void ReadXMLFile(string fileName)
{
try
{
bool blnReadFileFlag = true;
if (blnReadFileFlag)
{
File.ReadAllLines(fileName);
}
}
catch (Exception ex) when (Log(ex))
{
}
}
private bool Log(Exception e)
{
/* Log the error */
return false;
}
  1. Running the console application again, Visual Studio will break on the actual line of code that caused the exception:
  1. More importantly, the value of blnReadFileFlag is still in scope. This is because exception filters can see the state of the stack at the point where the exception occurred instead of where the exception was handled. Looking at the locals window in Visual Studio, you will see that the variables are still in scope at the point where the exception occurred:
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
52.15.42.128