.NET 异常处理机制的应用

      用常用的.NET的Try Catch  Finally    利用Catch处理错误(写入日志,抛出经过处理的异常给用户)

      1.自定义异常类型

      

//自定义异常类型必须继承与Exception类型
        public class ConvertException : Exception
        {
           //自定义异常构造函数,调用基类Message属性
            public ConvertException(string Message)
                : base(Message)
            {

            }
        }

     2.定义展示方法

     

  public class ExceptionHander
        {
            //参数是Exception类型
            //静态方法可以直接调用
            //本测试方法直接把错误Message属性抛出;
            public static void ExceptionThrow(System.Exception ex)
            {
                Page handler = HttpContext.Current.Handler as Page;
                ScriptManager.RegisterStartupScript(handler, HttpContext.Current.Handler.GetType(), "Message", "alert(\"" + ex.Message + "\");", true);
            }
        }

   3.在具体方法中使用

   

  try
            {
                string StrBox = txtBox.Text;
                if (Convert.ToInt32(txtBox.Text) > 10)
                {
                    //在具体业务中抛出异常信息(构造Message属性)
                    throw new ConvertException("录入数据大于10");
                }
            }
            //捕获特定异常信息
            catch (ConvertException ex)
            {
                //处理异常信息
                ExceptionHander.ExceptionThrow(ex);
            }
            catch (Exception ex)
            {
                ExceptionHander.ExceptionThrow(ex);
            }
            finally 
            {
                //最终的处理
            }
原文地址:https://www.cnblogs.com/jiangqiang/p/2667756.html