Wednesday, 26 September 2012

Custom exception in C#

When working with large projects with many integrating modules you will find developing custom exceptions imperative. In this post I will demonstrate how to create a simple custom exception.

The main motivation behind creating custom exceptions is that it improves code quality through simplified and improved error handling. Custom exception achieves improved error handling through separating application specific errors and other exception. When developing application modules you get to create object with specific responsibilities, at the same time you think around violations that would occur example invalid data or violation of logical constraints and throw relevant exceptions.

Here is an example of a custom exception for a login module.

Define a class and inherit the Exception class

using System; 
using System.Runtime.Serialization;

namespace LoginException
{
public sealed class LoginException : Exception
{
public LoginException()
: base() { }

public LoginException(string message)
: base(message) { }

public LoginException(string format, params object[] args)
: base(string.Format(format, args)) { }

public LoginExeption(string message, Exception innerException)
: base(message, innerException) { }

public LoginException(string format, Exception innerException, params object[] args)
: base(string.Format(format, args), innerException) { }

public LoginException(string message, Boolean LogError ,Exception innerException)
: base(message, innerException) {

if (LogError){
LogMessage(innerException,message);
}
}
public LoginException(string format, Boolean LogError, Exception innerException, params object[] args)
: base(string.Format(format, args), innerException) {

if (LogError){
LogMessage(innerException, string.Format(format, args));
}
}


private void LogMessage(Exception ex,string message)
{

try
{
if (!System.IO.Directory.Exists(Properties.Resource1.LogsPath))
System.IO.Directory.CreateDirectory(Properties.Resource1.LogsPath);

//Open a file and save the error message.

System.IO.StreamWriter file = new System.IO.StreamWriter( Properties.Resource1.LogsPath + "\\log " + DateTime.Now.ToString("ddMMyyHHmmss") + ".txt");

file.WriteLine(message + Environment.NewLine + ex.StackTrace);
file.Close();
}
catch
{

}
finally { }
}

}

}





How do we implement the class after defining it:



1. You can use the custom exception with a try catch statements as done below.




try 
{
//Code to execute here
}
catch (LoginException ex)
{
//do something

}









note better that this exception will only catch exception of type LoginException. You can improve on this to handle any other regular exception.




try{

//Code to execute here

}
catch (LoginException ex)
{

//do something

}

catch (Exception ex)
{
throw new LoginException(“error login in”,True,ex)
}



1 comment:

Comment