Pages

Wednesday, May 22, 2013

custom exception in c#

If  you want to create a custom exception class you can do it bye creating your own class inhering from "ApplicationException".

Please see the below code for the sample. In the code we are also logging the Error message when ever an exception is encoutered into the error log file.

sample Code1:

public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
int a = 3000;
 try
{
Salary ss = new Salary(a);
}
catch (CustSalException cse)
{
File.WriteAllText(@”C:\error.txt”, “Error Message:”+cse.msg);
}
}
}
public class Salary
{
private int _salary;
public Salary(int sal)
{
if (_salary < 5000)
{
CustSalException ee = new CustSalException();
ee.msg = “Salary Should be more than 5000rs”;
throw ee;
}
else
 _salary = sal;
}
}
public class CustSalException : ApplicationException
{
public string msg;
}

Sample Code2:(for SQL)

In the following example, I throw my own custom Exception object using the caught DataAdapterException as an InnerException.

try
{
 myConnection.Open();
 myDataAdapter.Fill(ds_records);
}

catch(Exception err)
{
 throw new MyCustomException(
              "Database error: Unable to fill dataset", err);
}

finally
{
 connection.Close();
}




Now lets make the MyCustomException. First off, lets make a base class _ErrorException
which inherits from the Exception class and write the following methods.
 We'll make the class Serializable, so that .NET is able to serialize the Exception.
If the exception is ever used in a remoting context, exceptions on the server are serialized
and remoted back to the client proxy. These base constructors are called each time we create a new Exception.



[Serializable]
public class _ErrorException : Exception
{
public string ErrorMessage
{
get
{
    return base.Message.ToString();
}
}

public _ErrorException(string errorMessage)
                   : base(errorMessage) {}

public _ErrorException(string errorMessage, Exception innerEx)
                   : base(errorMessage, innerEx) {}
}


Now lets create a class MyCustomException which inherits from _ErrorException:


public class MyCustomException : _ErrorException
{
public InternalErrorException(string errorMessage)
                             : base(errorMessage) {}  

public InternalErrorException(string errorMessage, Exception innerEx)
                             : base(errorMessage, innerEx) {}
}


That's about it. Now, from the business layer of my application,
I can track back to the original DataAdapterException and its original error message,
but also find out other places in the code affected by the error

No comments:

Post a Comment