c# - define new excptions

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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值