Microsoft state that if you want to raise custom exceptions in your application then you should derive them from the ApplicationException class and not the Exception class.
ApplicationException is thrown by a user program, not by the common language runtime. If you are designing an application that needs to create its own exceptions, derive from the ApplicationException class. ApplicationException extends Exception, but does not add new functionality. This exception is provided as means to differentiate between exceptions defined by applications versus exceptions defined by the system.
However, the blog entry by Microsoft’s Brad Adams states that ApplicationException should not be used !
I found that descending from Exception, at least gives a nice error message detailing the exception that was raised as opposed to ApplicationExceptiosn, “Application Error ocurred” message.
So how do we serialize a custom exception class ?
Step 1) Add the Serializable attribute to the exception
Step 2) Provide a contructor that takes the serialization information and context e.g. MyException(SerializationInfo info, StreamingContext context)
Step 3) If you have a constructor that passes state information to the exception to be included in the data collection ensure this is copied from the exception object to the info in the serialization constructor (step2)
e.g.
[csharp]
[Serializable]
public class MyException : Exception
{
public MyException(String sessionId)
: base()
{
this.Data.Add(”SessionID”, sessionId);
}
public MyException(SerializationInfo info, StreamingContext context)
: base(info, context)
{
info.AddValue(”SessionID”,Data["SessionID"]);
}
public override void GetObjectData(SerializationInfo info, StreamingContext context)
{
base.GetObjectData(info, context);
}
}
[/csharp]
Recent Comments