加入收藏 | 设为首页 | 会员中心 | 我要投稿 南京站长网 (https://www.025zz.com.cn/)- 自然语言处理、建站、经验、云计算、图像分析!
当前位置: 首页 > 综合聚焦 > 编程要点 > 语言 > 正文

C# 自定义异常汇总及严格遵循几个原则

发布时间:2023-06-12 16:00:37 所属栏目:语言 来源:未知
导读:   在C#中所有的异常类型都继承自System.Exception,也就是说,System.Exception是所有异常类的基类. 总起来说,其派生类分为两种:



  1. SystemException类: 所有的CLR提供的异常类
  在C#中所有的异常类型都继承自System.Exception,也就是说,System.Exception是所有异常类的基类. 总起来说,其派生类分为两种:
 
  1. SystemException类: 所有的CLR提供的异常类型都是由SystemException派生。
 
  2. ApplicationException类: 由用户程序引发,用于派生自定义的异常类型,一般不直接进行实例化。
 
  创建自定义异常类应严格遵循几个原则
 
  1. 声明可序列化(用于进行系列化,当然如果你不需要序列化。那么可以不声明为可序列化的)
 
  2. 添加一个默认的构造函数
 
  3. 添加包含message的构造函数
 
  4. 添加一个包含message,及内部异常类型参数的构造函数
 
  5. 添加一个序列化信息相关参数的构造函数.
 
  代码如下:
 
  using System;
 
  using System.Collections.Generic;
 
  using System.Linq;
 
  using System.Text;
 
  using System.IO;
 
  using System.Runtime.Serialization.Formatters.Binary;
 
  namespace ConsoleApplication3
 
  {
 
  [Serializable] //声明为可序列化的 因为要写入文件中
 
  public class PayOverflowException : ApplicationException//由用户程序引发,用于派生自定义的异常类型
 
  {
 
  /// <summary>
 
  /// 默认构造函数
 
  /// </summary>
 
  public PayOverflowException() { }
 
  public PayOverflowException(string message)
 
  : base(message) { }
 
  public PayOverflowException(string message, Exception inner)
 
  : base(message, inner) { }
 
  //public PayOverflowException(System.Runtime.Serialization.SerializationInfo info,
 
  // System.Runtime.Serialization.StreamingContext context)
 
  // : base(info, context) { }
 
  }
 
  internal class Employee
 
  {
 
  public int ID { get; set; }
 
  public string Name { get; set; }
 
  /// <summary>
 
  /// current pay
 
  /// </summary>
 
  public int CurrPay { get; set; }
 
  public Employee() { }
 
  public Employee(int id, string name, int currpay)
 
  {
 
  this.ID = id;
 
  this.Name = name;
 
  this.CurrPay = currpay;
 
  }
 
  /// <summary>
 
  /// 定义一个GiveBunus的虚方法以供不同的派生类进行重载
 
  /// </summary>
 
  /// <param name="amount">奖金额度</param>
 
  public virtual void GiveBunus(int amount)
 
  {
 
  //用一个临时变量记录递增之前的值
 
  var pay = CurrPay;
 
  this.CurrPay += amount;
 
  if (CurrPay > 10000)
 
  {
 
  //发生异常,将CurrPay的值进行恢复,
 
  //并抛出异常,外部程序捕获次异常
 
  this.CurrPay = pay;
 
  var ex = new PayOverflowException("The employee's max pay should be no more than 10000.");
 
  throw ex;
 
  }
 
  }
 
  }
 
  class Program
 
  {
 
  static void Main(string[] args)
 
  {
 
  Console.WriteLine("**** 创建Employee对象,并用try/catch捕获异常 *****");
 
  var emp = new Employee(10001, "Yilly", 8000);
 
  try
 
  {
 
  emp.GiveBunus(3000);
 
  }
 
  catch (PayOverflowException ex)
 
  {
 
  Console.WriteLine("异常信息:{0}/n发生于{1}类的{2}方法", ex.Message,
 

(编辑:南京站长网)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章