Exception Management Techniques in Dot Net


A proper exception management strategy is essential in all but the simplest applications. Commonly you will want to include logging with your exception handling. Logged exceptions are a key tool to diagnosing and fixing runtime problems that occur within an application.

Exception Management



A proper exception management strategy is essential in all but the simplest applications. Commonly you will want to include logging with your exception handling. Logged exceptions are a key tool to diagnosing and fixing runtime problems that occur within an application.

A good exception management approach involves two different aspects:

Throwing Exceptions



Throw existing framework exceptions if they fit, don't create your own custom exceptions when it is not necessary. Introduce a new exception class when it enables a programmer to take a different action in code based on the exception class.
Throw input validation exceptions liberally
Throw an InvalidOperationException if a property set or method call is not appropriate given the object's current state.
Throw an ArgumentException or a class derived from ArgumentException if invalid parameters are passed
In general throw an exception if your method can't do what it says it does. For example, if your method is "SaveCustomer" and the method can't do that then throw an exception.
Return null for extremely common error cases. For example, Open returns null if the file is not found, but throws an exception if the file is locked.
If you have to throw a new exception from inside an exception handler always include the existing exception as the inner exception.
If you need to create your own custom exception make sure to mark them as Seriablizable.
Design classes so that an exception is never thrown in normal use. For example, a FileStream class exposes another way of determining whether the end of the file has been reached. This avoids the exception that is thrown if you read past the end of the file.
Do Not expose any sensitive data through a propagated exception. For example, in a data layer you may have a database connection issue and if the connection fails the exception may contain information about the attempted connection (i.e. user id and server name) – this is information we don't want to reveal to users of the application (or library). In this case log the specifics of the exception and throw an alternative exception back to the caller that informs them of the problem but hides the sensitive details.

Catching Exceptions



When it comes to exception handling less is often more. In typical well written code you will see more try/finally blocks than you will try/catch blocks.
Create a global level exception handler that catches (and logs) all unhandled exceptions. If left unhandled, exceptions will cause the process to terminate (for client type applications) or the Yellow Screen of Death to appear for web applications. These scenarios are easily avoidable by properly handling any unhandled exception at a global level.
When needing to handle specific exception always order exceptions in catch blocks from the most specific to the least specific. This technique handles the specific exception before it is passed to a more general catch block.
Don't catch exceptions you can't do anything about. It's likely if you could do something about it, it wouldn't be exceptional, and you might consider calling TryParse, or File.Exists, or whatever it takes to prevent that exception.
Exceptions should be an indication of failure and not a means to control normal program flow. Code that makes decisions based around exceptions (or buries them) should be strongly considered for refactoring. It is not always possible to avoid this but in general this should be avoided.
If you do need to catch an exception and then rethrow it you should use "throw" not "throw ex" as you will lose the call stack and context data.
For additional information see Microsoft's Exception Handling guidance.


More articles: Exception Management

Comments

Author: Phagu Mahato08 Nov 2013 Member Level: Gold   Points : 0

Exception handling separates this logic. It simplifies management flow.Exceptions in C# give a structured, uniform, and type-safe method of handling each system-level and application-level error conditions. Exceptions or errors ar uncommon occurrences that happen inside the logic of AN application. you can not program for each possibility; thus, they're close. If AN exception happens inside AN application, the user is conferred with a yellow page that appears ugly. So, however does one modify these situations. you utilize exception handling techniques in ASP.NET.

Program that throws an exception in C#


using System;

class Program
{
static void Main()
{
try
{
int value = 1 / int.Parse("0");
Console.WriteLine(value);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
}


There are following ways to handle exceptions/errors in ASP.NET:

[1] try-catch block. This is also called Structured Exception Handling (SEH).


try
{
con = new SqlConnection("integrated security=SSPI;
data source= (local);persist security info=False;
initial catalog=Example");
da = new SqlDataAdapter("Select * from notexist", con);
ds = new DataSet();
da.Fill(ds);
}
catch(SqlException ex)
{
return "Unsuccessful " + ex.Message;
}
finally
{
con.Dispose();
}
return "Connection Successful";


[2] Error Events.

private void Page_Error(object sender, System.EventArgs e)
{
Exception ex = Server.GetLastError();
Response.Write("Error Handling in Page
");
}
protected void Application_Error(Object sender, EventArgs e)
{
Exception ex = Server.GetLastError();
Response.Write("Error from Application
");
Server.ClearError();
}
protected void Global_Error(Object sender, EventArgs e)
{
Exception ex = Server.GetLastError();
Response.Write("Error from Global
");
}



  • Do not include your name, "with regards" etc in the comment. Write detailed comment, relevant to the topic.
  • No HTML formatting and links to other web sites are allowed.
  • This is a strictly moderated site. Absolutely no spam allowed.
  • Name:
    Email: