If appropriate, you should best use built-in exceptions if the meansing is obvious. however, you do have the need to define your own set of exception. The custom exception that you defined may/may not have extra fields/information, because an exception type itself is meaningful enough in certain situation.
Suppose you do, let see an simple exception defintion, which does not have any extra information, here is the definition.
[Serializable]
public class CustomException: Exception
{
public CustomException() { }
public CustomException(string message) { }
public CustomException(string message, Exception inner) : base(message, inner)
{
}
public CustomException(SerializationInfo info, StreamingContext context)
: base(info, context)
{ }
}
Severl points worth mentioning:
- There are several overloads, normally you would define a void, a string message only, and a string message with an inner message - in total three overloads.
- If your exception needs to communicate with others (cross machine/process) boundary, you may want to provide one that has the Serialization and StreamingContext to marshall the exception.
- if you decide to have Serialization and StreamingContext, you might want to make your Exception serialzable
定义自定义异常
本文介绍了如何定义自定义异常,包括几种不同的构造函数重载方法,以及何时需要提供序列化和流化上下文来跨进程传递异常。

被折叠的 条评论
为什么被折叠?



