`

c# - define new excptions

    博客分类:
  • C#
c# 
阅读更多

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
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics