C Sharp Programming/Exceptions

Introduction
Software Programmers write code to perform some desired actions. But every software may fail to perform its desired actions for internal or external reasons. The exception handling system in the C# language allows the programmer to handle errors or anomalous situations in a structured manner that allows the programmer to separate the normal flow of the code from error-handling logic.

An exception can represent a variety of abnormal conditions that arise during the execution of the software. Such conditions can be internal or externally caused. External conditions of execution failures include, for example, network failures in connecting to a remote component, inadequate rights in using a file/system resource, out of memory exceptions or exceptions thrown by a web service etc. These are mainly due to failures thrown by environment components on which our application depends, e.g. the operating system, the .NET runtime or external applications or components. Internal failures may be due to software defects, designed functional failures (failures required as per business rules), propagated external failures, e.g. a null object reference detected by the runtime system, an invalid input string entered by a user and detected by application code, or a user requesting to withdraw a larger amount than the account balance (business rule).

Code that detects an error condition is said to throw an exception and code that handles the error is said to catch the exception. An exception in C# is an object that encapsulates various pieces of information about the error that occurred, such as the stack trace at the point of the exception and a descriptive error message. All exception objects are instantiations of the class or a child class of it. There are many exception classes defined in the .NET Framework used for various purposes. Programmers may also define their own class inheriting from or some other appropriate exception class from the .NET Framework.

Microsoft recommendations prior to version 2.0 recommended that a developer's exception classes should inherit from the exception class. After 2.0 was released, this recommendation was made obsolete and users' exception classes should now inherit from the class.

Overview
There are three code definitions for exception handling. These are:


 * / - Do something and catch an error, if it should occur.
 * // - Do something and catch an error if it should occur, but always do the.
 * / - Do something, but always do the . Any exception that occurs, will be thrown after.

Exceptions are caught in the order from most specific to least specific. So for example, if you try and access a file that does not exist, the CLR would look for exception handlers in the following order:


 * (base class of )
 * (base class of )
 * (base class of )
 * (base class of )

If the exception being thrown does not derive from or is not in the list of exceptions to catch, it is thrown up the call stack.

Below are some examples of the different types of exceptions

/
The / performs an operation and should an error occur, will transfer control to the catch block, should there be a valid section to be caught by:

Here is an example with multiple catches:

In all statements you may omit the type of exception and the exception variable name:

//
Catching the problem is a good idea, but it can sometimes leave your program in an invalid state. For example, if you open a connection to a database, an error occurs and you throw an exception. Where would you close the connection? In both the try AND exception blocks? Well, problems may occur before the close is carried out.

Therefore, the statement allows you to cater for the "in all cases do this" circumstance. See the example below:

Second Example

Notice that the SqlConnection object is declared outside of the //. The reason is that anything declared in the / cannot be seen by the. By declaring it in the previous scope, the block is able to access it.

/
The / block allows you to do the same as above, but instead errors that are thrown are dealt with by the catch (if possible) and then thrown up the call stack.

Re-throwing exceptions
Sometimes it is better to throw the error up the call stack for two reasons.


 * 1) It is not something you would expect to happen.
 * 2) You are placing extra information into the exception, to help diagnosis.

How not to throw exceptions
Some developers write empty / statements like this:

This approach is not recommended. You are swallowing the error and continuing on. If this exception was an or a, it would not be wise to continue. Therefore you should always catch what you would expect to occur, and throw everything else.

Below is another example of how exceptions are caught incorrectly

As you can see, the will be caught by the  block, but it is being ignored completely! This is bad programming as you are ignoring the error.

The following is also bad practice:

The CLR will now think the statement is the source of the problem, when the problem is actually in the try section. Therefore never re-throw in this way.

How to catch exceptions
A better approach would be:

The keyword means preserve the exception information and throw it up the call stack.

Extra information within exceptions
An alternative is to give extra information (maybe local variable information) in addition to the exception. In this case, you wrap the exception within another. You usually use an exception that is as specific to the problem as possible, or create your own, if you cannot find out that is not specific enough (or if there is extra information you would wish to include).