During development, I always look for an optimal and efficient way to achieve a goal. Last time, I came with the way to log the exceptions along with method parameters for which exception has thrown.
Generally, for large scale projects (i.e. having multiple modules talks to each other), one should define custom exceptions.
Define custom exception class:
[Serializable]
public class CustomException : Exception
{
public CustomException()
: base() { }
public CustomException(string message)
: base(message) { }
public CustomException(string format, params object[] args)
: base(string.Format(format, args)) { }
public CustomException(string message, Exception innerException)
: base(message, innerException) { }
public CustomException(string format, Exception innerException, params object[] args)
: base(string.Format(format, args), innerException) { }
protected CustomException(SerializationInfo info, StreamingContext context)
: base(info, context) { }
}
Example:
1. Throw exception with out message
throw new CustomException()
2. Throw exception with simple message
throw new CustomException(message)
3. Throw exception with message format and parameters
throw new CustomException("Exception with parameter value '{0}'", param)
4. Throw exception with simple message and inner exception
throw new CustomException(message, innerException)
5. Throw exception with message format and inner exception. Note that, the variable length params are always floating.
throw new CustomException("Exception with parameter value '{0}'", innerException, param)
6. The last flavor of custom exception constructor is used during exception serialization/deserialization.