Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations biv343 on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

C# Error Handling - File Not Found

Status
Not open for further replies.

tahirk

Programmer
Oct 24, 2005
47
GB
Hi,

I am fairly new to C# but learning quickly (ex Delphi coder and C coder).

So far I have managed to learn allot without digging into books etc however I want to know how to do things the proper way so I can then learn my own solutions to a problem.

Currently I am working on a small Windows application that monitors various services on a series of remote machines. So far I have been able to create a class that monitors each service and reports the state and also some classes to read/write to a text log file and insert events in the Windows Eventlog.

The data is read in via an XML file and I am using the DataSet class to handle the file; everything works so far i.e I am able to enumerate through the XML file and then based on the whats found (e.g remote hostname, ip address and services), I can then call my service monitor function to go check the machine and then report back its findings.

However I am not too clear on how to do the error handling, so far I have been playing about with the Try..catch..finally code but not having much luck as I seem to be dereferencing something along the way (I miss Delphi :p ). Here is the offending line:
Code:
FileStream xmlschemafile = new FileStream("remotehosts.xsd",FileMode.Open,
			FileAccess.Read,FileShare.Read);
I encolsed the above in a Try..catch..finally statement and then used tested this in seperate file to ensure the error handling worked (I moved the source xsd file), and sure enough my custom error message popped up "File is not matey!". However when I then tested the same in the main class I was not able to compile the code.

Outside of the Try..catch code I have the following lines to then read the data in the xml file:
Code:
 ds.ReadXmlSchema(xmlschemafile);
 xmlschemafile.Close();
When building I get an error advising no reference was found in my main class for xmlschemafile.

I am sure this is a no brainer for someone, I am not an active coder, I simply design solutions to help my main role as a system admin.

Thanks in advance,

Fz
 
Just to add to the above post, I use the above code to read the schema file associated to my XML file and then use the same above methods to read the XML file itself:
Code:
FileStream xmldatafile = new FileStream("remotehosts.xml", FileMode.Open,			FileAccess.Read,FileShare.ReadWrite);
ds.ReadXml(xmldatafile);
xmldatafile.Close();

Obviously I need to do the same with the above as well - even better would be to create a class that can handle my custom exceptions to cater for things like:

[li]remote host not found[/li]
[li]service xxxxxx not found[/li]
[li]log file not found[/li]
[li]Eventlog entry failed[/li]

You get the general idea of what I am doing (I do similar things in WSH & VBS for most of my sys admin stuff but VBS is so out of date!).

Cheers,

Fz
 
Okay,

Just found a really cool button on this site, called 'Search'.. amazed I missed it the first time ;)

Had a good read through the various threads on C# error handling and was a little amsued by the VB vs C# error handling threads. Being a Delphi coder I find the try..catch..finally a natural progression (but then the creater of C# was also the brains behind Delphi..) but this is another discussion entirely.

I realized the scope had been lost somewhere because of the way I was placing the try..catch..finally satements so I simply rejigged everything to look like this:

Code:
// start of code
[COLOR=blue]public[/color] static void Main()
{
  [COLOR=blue]try[/color]
  {
    [COLOR=green]// some code here[/color]
    FileStream xmlschemafile ............ 
    [COLOR=green]// read the schema file[/color]
    ds.ReadXmlSchema(xmlschemafile);
    xmlschemafile.Close();
    
    [COLOR=green]// yet more code[/color]
    [COLOR=green]// the rest of the app[/color]
  }
  [COLOR=green]// start of my exception handling stuff[/color]
  [COLOR=blue]catch[/color] (FileNotFoundException e)
  {
    [COLOR=green]// do something with this[/color]
    [COLOR=green]// write to eventlog[/color]
    [COLOR=green]// write to log file[/color]
    [COLOR=green]// write to console (if app was run in user mode[/color]
  }
  // another catch
  [COLOR=blue]catch[/blue] (Exception e)
  {
    [COLOR=green]// do something with this
    // ...
    // ...[/color]
  }
  [COLOR=blue]finally[/color]
  {
    [COLOR=green]// clean up code, write to eventlog (trap this as well)
    // write to log file
    // exit now[/color]
  }
}
[COLOR=green]// end of main code[/color]

The above compiles but I am too tired to go through and test it fully. I have read allot about C# error handling but nothing explaining the rules of how it should fit into more real life code instead of the simple divide-by-zero examples ;)

Any input much appreciated..

Fz
 
How do I capture events that I are unknown or those that there is no standard exception handling (FileNotFoundExcpetion etc)?

I want to capture events like a service being down etc, do I have to design some custom error handling for this?

Cheers,

Fz
 
All exception objects inherit from System.Exception, so you can use a [tt]try {} catch (Exception ex) {}[/tt] structure to implement a "catch-all" case.

You can have multiple catch statements, and you want to organize them in progression from the most specific to the most general:
Code:
try
{
  // Something goes wrong
}
catch (FileNotFoundException fnfex)
{
}
catch (Exception ex)
{
}

Chip H.


____________________________________________________________________
Donate to Katrina relief:
If you want to get the best response to a question, please read FAQ222-2244 first
 
Chip,

Thanks for the confirmation. I have actually advanced quite a bit since the above hurdle and in doing so have learn't allot about C# (I never realized it was this easy to transfer my knowledge of C and Delphi to C#).

I created a new bit of code and templated the class so it looked like this:
Code:
[COLOR=blue]public class[/color] MyClassTemplate
{
   [COLOR=green]// setup some static values and global vars
   .......
   .......[/color]

  [COLOR=blue]public static void[/color] Main()
  {
     [COLOR=blue]try[/color]
     {
       [COLOR=green]// start of main code to trap[/color]
     }
     [COLOR=blue]catch[/color] ([COLOR=green]//add your exception here[/color])
     {
       [COLOR=green]do something[/color]
     }
     [COLOR=blue]catch[/color] ([COLOR=green]//another catch here[/color])
     {
       [COLOR=green]do something[/color]
     }
     [COLOR=blue]finally[/color]
     {
       [COLOR=green]clean up code and exit[/color]
     }
}

Initially I had my functions sitting blew with allot of stuff instantiated in the code but after some careful planning I was able to create an include file that contained all of my various functions. By doing so I had cleaned up my main code so it was readible and should only contain calling parameters, all events etc are handled by the functions in the include file.

Each time I wanted to use a function I had created I simply used this line:
Code:
Functions.CommonFunctions.MyFunction([COLOR=green]//parameter 1, parameter 2 etc[/color]);

Easy, a total no brainer for folks on here but for me this was a small victory as it proved to me how easy it is to work with the .NET Framework and C# - in the process I learn't how to create my own namespace and expose the underlying class to access the features present (like functions etc).

The terminology throws me coming from Delphi but its all simple OOP stuff, in fact I find understand OOP easier through the use of VS.NET and the framework than opening up books and reading masses of text that is not legible because some expert decided to geek out ;)

Through what I learned I have now created a template that I can use to construct other new code and also made my functions generic and reusable by putting them under their own namespace; all that is left to do is to add some error handling to the fuctions and job done.

Now I see where all of the System.Data etc namespaces sit and how everything works.. I think.

Adios,

Fz
 
in fact I find understand OOP easier through the use of VS.NET and the framework
Intellisense is a huge timesaver!

Best of luck.
Chip H.


____________________________________________________________________
Donate to Katrina relief:
If you want to get the best response to a question, please read FAQ222-2244 first
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top