Errors and Exception Handling
When something goes wrong while a C# program is running, an exception occurs. Exceptions stop the current flow of the program, and if nothing is done, the program simply stops running. Exceptions can be caused by a bug in the program-for example, if a number is divided by zero- or can be a result of some unexpected input, such as a user selecting a file that doesn't exist. As a programmer, you need to allow your program to deal with these problems without crasing to a halt.
C# provides several keywords - try, catch, and finally- that allow programs to detect exceptions, deal with them, and continue running. They are a very useful tool for making your applications more reliable.
Try and Catch
The try and catch keywords are used together. Use try to enclose the block of code you are concerned might generate an exception, and catch to contain the code that will be executed if the exception occurs.
It's a good programming practice to be specific about the type of exception your catch code is detecting. Each try can have multiple catch statements, each dealing with a different exception.
finally Blocks
Code contained in a finally block is always executed, whether or not an exception occurs. Use the finally block to make sure resources are returned: for example, to make sure that a file is closed.
Using Exception Handling
Exceptions aren't always a sigh that a catastrophic problem has occurred in your program. Often they are a convenient way of leaving a section of code that is no longer relevant, or a signal that a method has been unsuccessful. Many of the .NET Framework class methods create exceptions to warn of a particular condition.
You can also cause your own exceptions using the throw keyword.