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

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

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

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

     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("无效的操作异常!");
    }
    }

    读者也可以自定义错误处理信息或想要进行的其他操作。

  • 相关阅读:
    HDOJ 4747 Mex
    HDU 1203 I NEED A OFFER!
    HDU 2616 Kill the monster
    HDU 3496 Watch The Movie
    Codeforces 347A A. Difference Row
    Codeforces 347B B. Fixed Points
    Codeforces 372B B. Hungry Sequence
    HDU 1476 Sudoku Killer
    HDU 1987 How many ways
    HDU 2564 词组缩写
  • 原文地址:https://www.cnblogs.com/hmiinyu/p/2245578.html
Copyright © 2011-2022 走看看