Translate

Wednesday, February 2, 2011

Exception handling in C# ( C sharp)


    An exception or error in code is something that causes the system to abruptly stop from executing the code. This can happen in one of two ways.

1>Run time Exception: These are exceptions defined by the .net framework. These errors are thrown by the CLR.
Examples
·         If you try something like 1/0 the .net frame work CLR will throw a System.DivideByZeroException. 
·         Suppose you try to access an array element that does not exist, the CLR would throw a System.IndexOutOfRangeException.

2>Application Exception: These exceptions are defined by the developer of the application.  These errors are thrown by the application logic and not the CLR. The developer does this by defining a class that inherits from the System.ApplicationException class or System.Exception class. One common use of application exception would be to throw generic exceptions.

How to handle an error in C#?

The sample code below explains how to handle error.
try
{
//some code
}
catch (Exception ex)
{
}   
finally
{
//clean up code (close connections etc)
}

This is how it works
1>The code tries executing what’s inside the try block.
2>If that fails, it enters the catch block (otherwise it directly goes to finally block)
3>After executing what’s inside the catch block, it enters the finally block.

Certain points to note.
·         Finally block is always executed, regardless of whether or not an error occurs.
·         If you don’t re throw the error inside the catch block, after the finally block the code continues execution as if nothing went wrong. The application doesn’t abort.
·         If you throw the error again inside the catch block, the application aborts after the finally block. In that case the error is called an unhandled exception.
·         If you use a try block, either a catch or finally block is necessary.

What’s explained above is a simplified version.

Some notes/best practices on error handling

Most of the below recommendations are Microsoft’s official recommendations

1>You should never catch a system exception unless your intention is to log it or to throw it again. For example
Reason: The code continues to execute as usual. It pretends nothing went wrong.

This code is NOT recommended.
try
{    int x = 0;
    int y = 1 / x;
}
catch
{
}

The code below is acceptable
try
{
int x = 0;
int y = 1 / x;
}
catch
{
    throw;
}

2>An empty throw is preferred over re throwing an exception
Reason: If you catch and re throw an exception the application thinks that the re throw location is the source of error. It wouldn’t know the original source of error.
For example in the code below, line 32 is a divide by zero error
This is wrong
Wrong way to handle exception

This is the right way to do it

Correct way to handle exception

3>An easy way to throw a custom error would be as shown below
try
{
Int deptNumber=int.Parse(txtDept.text. ToString());
}
catch
{
throw new Exception("Department number entered is invalid.");
}

3>It is a bad practice to use try catch block for adding functionality. It should only be used to handle errors.
Reason: Once the code enters the catch block, it is resource intensive. (Try block however is NOT resource intensive)

For example the code below should be avoided
try
{
    conn.Close();
}
catch
{    
}

Instead you should use something like
if (conn.State != ConnectionState.Closed)
{
    conn.Close();
}

4>According to some experts, a well written code has more try finally blocks and less try catch finally blocks.



Further Reading ( links to MSDN):


Creating and Throwing Exceptions (C# Programming Guide)
http://msdn.microsoft.com/en-us/library/ms173163.aspx

Exception Handling Statements (C# Reference)

No comments:

Post a Comment

Comments will appear once they have been approved by the moderator