Minimum code required to create a custom exception in C#
A simple custom exception class.
using System;
using System.Runtime.Serialization;
[Serializable]
public class CustomException : Exception {
public CustomException() { }
public CustomException(String message) : base(message) { }
public CustomException(String message, Exception inner) : base(message, inner) { }
protected CustomException(SerializationInfo info, StreamingContext context)
: base(info, context) { }
}
The exception class can also carry some additional data:
using System;
using System.Runtime.Serialization;
[Serializable]
public class CustomException : Exception {
readonly Int32 data;
public CustomException() { }
public CustomException(Int32 data) : base(FormatMessage(data)) {
this.data = data;
}
public CustomException(String message) : base(message) { }
public CustomException(Int32 data, Exception inner) : base(FormatMessage(data), inner) {
this.data = data;
}
public CustomException(String message, Exception inner) : base(message, inner) { }
protected CustomException(SerializationInfo info, StreamingContext context) : base(info, context) { }
public override void GetObjectData(SerializationInfo info, StreamingContext context) {
if (info == null)
throw new ArgumentNullException("info");
info.AddValue("data", this.data);
base.GetObjectData(info, context);
}
public Int32 Data { get { return this.data; } }
static String FormatMessage(Int32 data) {
return String.Format("Custom exception with data {0}.", data);
}
}
Consider creating a hierarchy of custom exceptions.
Also study the MSDN page Error Raising and Handling Guidelines. However, disregard the rule that new exception classes should derive from the ApplicationException class, and stick with the code analysis rule CA1058: Types should not extend certain base types.
Fork
0 Feedback
You must log in before you can give any feedback
You must log in before you can post a comment


637
0




Mark '.net' tag as 'like'
Mark '.net' tag as 'ignore'