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 crashing 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.
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. In this example, a calculation creates a division by zero exception, which is then caught. Without the try and catch blocks, this program would fail.
It's 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.
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.
Exceptions aren't always a sign 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. For example:
Use exceptions in your programs when you think there is a chance of some unexpected situation arising. For example, when dealing with input from a user, reading a file or accessing information from the Internet.