Csharp .Net Tutorial: Catching Errors

James Cloud
It is inevitable, in any programming language, that errors will be encountered and must be dealt with. Most errors cause the compiled application to crash and close itself if they are left untended. Sometimes you might like to allow errors but display your own error message.

To effectively deal with errors and error messages CSharp .Net give you the ability to use the try and catch methods.

The Try and Catch Methods

Using the try and catch method you easily retrieve detailed information about the error, display personally customized error messages, or ignore the error completely and move on to the next section of code.

Below is an example use of the try and catch method of error handling:

try
{
//Because the File is not there an error will be trigger or raised.
System.Diagnostics.Process.Start("c:\\this\\file\\isnt\\here.exe");
}
catch (Exception myerror)
{
//Tell the user there was an error and show the error's description
MessageBox.Show("There was an error: " + myerror.Message);
}

This will code will attempt to start an executable file that does not exist, thus raising an error event. When the error is encountered the catch method is addressed showing a message box that will display a description of the error.

To ignore the error simply replace the catch method like this:

try
{
//Because the File is not there an error will be trigger or raised.
System.Diagnostics.Process.Start("c:\\this\\file\\isnt\\here.exe");
}
catch {}

To get a description or detail information about the error that was raised simply read the string myerror.Message. By reading the error's description or message text you can differentiate between different error, hence giving you the ability to execute different code for different errors.

Conclusion

Now you can easily customize the way your application handles each error giving a personal response, using the CSharp .Net framework's try and catch error handling method.

Published by James Cloud

I like to program and do basically anything that has to do with technology and computers.  View profile

To comment, please sign in to your Yahoo! account, or sign up for a new account.