錯誤異常處理方法

來源:互聯網
上載者:User

我們都知道異常可以用  try-catch-finally來捕獲並處理異常,這是在程式運行時可以捕獲處理的。

下面介紹幾種開發上常用的錯誤處理

包括:

aps.net 異常處理

1、頁面級錯誤處理

2、應用程式級錯誤處理

3、應用程式配置

WinForm應用程式全域異常處理

 

 

一、asp.net頁面級錯誤處理

在單獨頁面中的錯誤。可以在page_error事件中添加處理邏輯代碼,通過Server.GetLastError()擷取當前頁面的錯誤。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace _22
{
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{

}



protected void Page_Error(object sender, EventArgs e)
{
string errMsg = "";
Exception currentError = Server.GetLastError();
errMsg += "系統發生錯誤:<br/>" +
"錯誤地址: " + Request.Url.ToString() + "<br/>" +
"錯誤資訊: " + currentError.Message.ToString() + "<br/>";
Response.Write(errMsg);
Server.ClearError();//要注意這句代碼的使用,清除異常。
}

}
}

如果少掉了server.clearError()方法的話,仍然會引發Application_Error的錯誤處理。

 

 

二、應用程式級錯誤處理

截獲整個應用程式中啟動並執行錯誤,可以在項目的Global.asax檔案中的 application_error 添加處理邏輯。

        protected void Application_Error(object sender, EventArgs e)
{
Exception ex = Server.GetLastError();
string errmsg = "";
string Particular = "";
if (ex.InnerException != null)
{
errmsg = ex.InnerException.Message;
Particular = ex.InnerException.StackTrace;
}
else
{
errmsg = ex.Message;
Particular = ex.StackTrace;
}
//AddLog(errmsg, Particular);
Server.ClearError();//處理完及時清理異常
}

 

 

 

三、應用程式配置

可以在web.config中配置一些常見錯誤的處理方法

  <system.web>
<customErrors mode="On" defaultRedirect="GenericErrorPage.htm">
<error statusCode="403" redirect="NoAccess.htm"/>
<error statusCode="404" redirect="FileNotFound.htm"/>
</customErrors>
</system.web>

其中各元素的用途如下。

1、mode:具有On , Off ,RemoteOnly 三種狀態。

     on:表示始終顯示自訂的資訊。

     off:表示始終顯示詳細的asp.net錯誤資訊。

     RemoteOnly:表示只對不在本地web伺服器上啟動並執行使用者顯示自訂資訊。

2、defaultRedirect:用於出現錯誤時重新導向的URL地址(可選)。

3、statusCode : 指明錯誤狀態代碼,表明一種特定的出錯狀態。

4、redirect : 錯誤的重新導向URL

 

 

四、winform應用程式全域異常處理

winform中沒有像asp.net的 application_error事件,但我們可以通過聲明委託的方式來實現全域的異常截獲。

Program.cs代碼

using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;

using System.Threading;

namespace _23
{
static class Program
{
/// <summary>
/// 應用程式的主進入點。
/// </summary>
[STAThread]
static void Main()
{
// 定義線程例外狀況事件
ThreadExceptionHandler handler = new ThreadExceptionHandler();
Application.ThreadException +=
new ThreadExceptionEventHandler(handler.Application_ThreadException);



Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}
}
}
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

using System.Threading;
namespace _23
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void button1_Click(object sender, EventArgs e)
{
throw new InvalidOperationException("無效的操作異常");
}
}



// 異常處理類.
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 ex)
{
string errorMessage = "錯誤資訊:\n\n" +
ex.Message + "\n\n" + ex.GetType() +
"\n\nStack Trace:\n" +
ex.StackTrace;
return MessageBox.Show(errorMessage,
"Application Error",
MessageBoxButtons.AbortRetryIgnore,
MessageBoxIcon.Stop);
}
}

}

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.