Hi.

So far I have been moving along relatively steadily with my learning of C#.
One thing I havently really bothered with yet is try and catch. The reason I havent looked
into this is I dont really know in what cases I would need to use it.

So my question is, In what kind of scenarios would I emloy them?

I know the question is a broad one, but it is what it is.

Appreciate any advice.

Edited 6 Years Ago by Suzie999: typo

Hi well i guess you could try this.

try {
Process.Start("calc.exe");
}
catch{
MessageBox.Show("Error in opening calculator");
}

Or maybe you could use it in this situation

try
{ 
File.Create("C:\\Users\\Familly\\test.txt");
            MessageBox.Show("Test file created");
}
catch{
MessageBox.Show("Error");
}

So basically the try/catch statment means this

try to create the file but if you cannot create the file display the error message.

Sorry but my earlier post seemed a bit wrong in context.
the try catch statment means that this
try to (do the action) but if the action thing cannot do the action, do something else .
in my earlier post it seemed it worked with System.IO.File.Create

NSSLTD

Thank you for your reply.

Would it be true to say that it is best used where a method has a viod return ?

I have been using a methods return value to dertimine if it was successfull or not you see.

Try/Catch generally should be used in any scenario where the outcome of your code is not 100% guaranteed to produce the desired result.

An example would be the file.create example that nssltd posted above but it could also be used for things like database manipulation (try to insert information and catch the error if it doesn't work).

Another component not mentioned above but still part of the try/catch family is "finally" which is a 'catch-all' piece of code which fires after both try and catch have completed their bits. Basically 'try' fires up it's piece of code and if it fails then 'catch' steps up and tries to salvage things so the program doesn't fail entirely. Once either of the first two is completed in what they're doing it moves on to 'finally' who steps in to do whatever needs to be done to finish up the task.

This is all part of the larger picture that is 'error handling' within the C# language. For some additional information about this I suggest reading the first 2-3 listings in this google search as, looking over the list, they all seem to be good reference points for beginner programmers.

Hope that helps :)

Comments
clear, to the point

It helps an awful lot, and I thank you muchly for it.

For me, a lot of the help documentation found through internet searches are overly complicated explanations, which can confuse a beginner. beginners need laymans explanations to get the gist before going on to fully understand the intricacies of the things they query (meaning me :) ).

Thats exactly what you have givem me.

Thanks.
Suze.

This question has already been answered. Start a new discussion instead.