c# 异常类用途及设计

来源:互联网 发布:云南师范网络教学平台 编辑:程序博客网 时间:2024/05/16 04:44

1:SystemException类:该类是System命名空间中所有其他异常类的基类。(建议:公共语言运行时引发的异常通常用此类)
2:ApplicationException类:该类表示应用程序发生非致命错误时所引发的异常(建议:应用程序自身引发的异常通常用此类),如果我们要自定义异常类,那么就应派生于它。
    #region CarIsDeadException, take three.
    [global::System.Serializable]
    public class CarIsDeadException : ApplicationException
    {
        public CarIsDeadException() { }
        public CarIsDeadException(string message) : base(message) { }
        public CarIsDeadException(string message, Exception inner)
            : base(message, inner) { }
        protected CarIsDeadException(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context)
            : base(info, context) { }

        // Feed message to parent constructor.
        private DateTime errorTimeStamp;
        private string causeOfError;
        public CarIsDeadException(string message, string cause, DateTime time)
            : base(message)
        {
            causeOfError = cause;
            errorTimeStamp = time;
        }
        public DateTime TimeStamp
        {
            get { return errorTimeStamp; }
            set { errorTimeStamp = value; }
        }
        public string Cause
        {
            get { return causeOfError; }
            set { causeOfError = value; }
        }
    }
    #endregion
    CarIsDeadException ex = new CarIsDeadException(string.Format("{0} has overheated!", petName),"You have a lead foot", DateTime.Now);
    catch (CarIsDeadException e)
    {
        Console.WriteLine(e.Message);
        Console.WriteLine(e.TimeStamp);
        Console.WriteLine(e.Cause);
    }
3:在catch块中产生了异常,处理如下
    catch (CarIsDeadException e)
    {
        try
        {
            FileStream fs = File.Open(@"C:/carErrors.txt", FileMode.Open);
        }
        catch (Exception e2)
        {
            throw new CarIsDeadException(e.Message, e2);
        }
    }