zoukankan      html  css  js  c++  java
  • C#的异常处理机制

    任何完美的应用程序和技术高明的程序员,都不可能是绝对不出差错的。与其追求完美无错的代码,还不如将程序中可能预知的异常在发布前进行很好的处理,可能是最有价值的。那么,C#是如何处理异常的呢?首先,我们从最普通的异常说起:

    使用try-catch-finally块捕获异常,基本格式如下:

    复制代码
     1 try
     2 {
     3     //获取并使用资源,可能出现异常
     4 }
     5 catch(DivideByZeroException de)
     6 {
     7 }
     8 catch(ArithmeticException ae)
     9 {
    10 }
    11 catch(Exception e)
    12 {
    13     //捕获并处理异常,当出现多个异常且异常类之间有继承关系(DivideByZeroException==>ArithmeticException==>Exception),
    14      //捕获顺序是子类在前,基类在后
    15 }
    16 finally
    17 {
    18     //无论什么情况(即使在catch块中return)下,都会执行该块的代码(如:关闭文件)
    19     //另外需要说明的是,在finally块中使用任何break、continue、return退出都是非法的。
    20 }
    复制代码


    ASP.NET异常处理

    除了以上的try-catch-finally的处理方式外,还有三种方式来捕获异常:

    1. 页面级错误处理(通过Page_Error事件)

    复制代码
    protected void Page_Error(object sender, EventArgs e)
    {
        string errorMsg = String.Empty;
        Exception currentError = Server.GetLastError();
        errorMsg += "系统发生错误:<br/>";
        errorMsg += "错误地址:" + Request.Url + "<br/>";
        errorMsg += "错误信息:" + currentError.Message + "<br/>";
        Response.Write(errorMsg);
        Server.ClearError();//清除异常(否则将引发全局的Application_Error事件)
    }
    复制代码

    2. 应用程序级(global.asax)错误处理(通过Application_Error事件)

    复制代码
    protected void Application_Error(object sender, EventArgs e)
    {
        Exception ex = Server.GetLastError();
        Exception iex = ex.InnerException;
        string errorMsg = String.Empty;
        string particular = String.Empty;
        if (iex != null)
        {
            errorMsg = iex.Message;
            particular = iex.StackTrace;
        }
        else
        {
            errorMsg = ex.Message;
            particular = ex.StackTrace;
        }
        //AddLog(errorMsg, particular);
        Server.ClearError();//处理完及时清理异常
    }
    复制代码

    3. 应用程序配置(web.config)

    复制代码
    <system.web>    
      <!--mode有三种值:On,Off,RemoteOnly,defaultRedirect出现错误重定向的URL-->
      <customErrors mode="On" defaultRedirect="ErrorPage.htm">
        <!--statusCode错误状态码,redirect错误重定向的URL-->
        <error statusCode="403" redirect="NoAccess.htm"/>
        <error statusCode="404" redirect="FileNoFound.htm"/>
      </customErrors>
    </system.web>
    复制代码

    WinForm应用程序异常处理 

    在WinForm的应用程序中,除了采用try-catch-finally的方式外,如何实现全局的异常处理呢?因为不具有Application_Error事件,但可以通过委托的方式来实现。

    复制代码
    internal class ThreadExceptionHandler
    {
        //实现错误异常事件
         public void Application_ThreadException(object sender, ThreadExceptionEventArgs e)
        {
            try
            {
                //如果用户单击"Abort"则退出应用程序
                  DialogResult result = ShowThreadExceptionDialog(e.Exception);
                if (result == DialogResult.Abort)
                {
                    Application.Exit();
                }
            }
            catch
            {
                try
                {
                    MessageBox.Show("严重错误", "严重错误", MessageBoxButtons.OK, MessageBoxIcon.Stop);
                }
                finally
                {
                    Application.Exit();
                }
            }
        }
        private DialogResult ShowThreadExceptionDialog(Exception e)
        {
            string errorMsg = "错误信息:\t\t" + e.Message + "\t\t" + e.GetType() + "\t\t" + e.StackTrace;
            return MessageBox.Show(errorMsg, "Application Error", MessageBoxButtons.AbortRetryIgnore, MessageBoxIcon.Stop);
        }
    }
    static class Program
    {
        ///<summary>
        /// The main entry point for the application.
        ///</summary>
        [STAThread]
        static void Main()
        {
            ThreadExceptionHandler handler = new ThreadExceptionHandler();
            Application.ThreadException += new ThreadExceptionEventHandler(handler.Application_ThreadException);
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new frmEvent());
        }
    }
    public partial class frmEvent : Form
    {
        private void btnException_Click(object sender, EventArgs e)
        {
            throw new InvalidOperationException("无效的操作异常!");
        }
    }
    复制代码

     LinkFrom:http://www.cnblogs.com/hmiinyu/archive/2011/11/11/2245578.html

     

    VS2008 插件 CodeRushX 下载地址

    Posted on 2012-07-02 23:05 NoNames 阅读(18) 评论(0编辑 收藏 

    http://go.devexpress.com/CodeRushX.aspx

     
  • 相关阅读:
    mysql alter table时的表锁是mysql服务层加的还是存储引擎加的
    show databases in redis
    Docker-compose中的使用技巧
    debian切换源
    C# MVC(File)控件多张图片上传加预览
    C# DateTime日期格式化
    DropDownList的使用,RadioButtonList的使用
    access数据库连接问题
    动态获取ul,li的数据
    Dungeon Game
  • 原文地址:https://www.cnblogs.com/Leo_wl/p/2574232.html
Copyright © 2011-2022 走看看