2009-11-30 30 views
1

我有嵌套的try catch塊嵌套的try-catch與Reponse.Redirect在ASP.NET

try 
{ 
    // statements 
    try 
    { 
     // statements 
    } 
    catch(SqlException sqlex) 
    { 
     Response.Redirect(@"~/Error.aspx?err=" + Server.UrlEncode(sqlex.Message) 
           + "&src=" + Server.UrlEncode(sqlex.ToString())); 
    } 
    catch (Exception ex) 
    { 
     Response.Redirect(@"~/Error.aspx?err=" + Server.UrlEncode(ex.Message) 
           + "&src=" + Server.UrlEncode(ex.ToString())); 
    } 
    finally 
    { 
     conn.Close(); 
    } 
} 
catch (Exception ex) 
{ 
    Response.Redirect(@"~/Error.aspx?err=" + Server.UrlEncode(ex.Message) 
          + "&src=" + Server.UrlEncode(ex.StackTrace)); 
} 
finally 
{ 
    conn.Close(); 
} 

如果SqlExeception在內部第一個catch塊捕獲,然後又因爲的try ... catch包圍Response.Redirect,由傳輸生成的ThreadAbortException被外部catch塊捕獲。

我該如何解決這個問題?謝謝!

+0

爲什麼你需要嵌套try catch? – 2009-11-30 14:02:02

回答

2

閱讀this article

你可以做什麼最簡單的是不是你的try/catch線束裏面重定向:

string url ; 
try 
    { 
      // statements 
      try 
      { 
      } 
      catch(SqlException sqlex) 
      { 
       url = @"~/Error.aspx?err=" + Server.UrlEncode(sqlex.Message) + "&src=" + Server.UrlEncode(sqlex.ToString()); 
      } 
      catch (Exception ex) 
      { 
       url = @"~/Error.aspx?err=" + Server.UrlEncode(ex.Message) + "&src=" + Server.UrlEncode(ex.ToString()); 
      } 
      finally 
      { 
       conn.Close(); 
      } 
    } 
    catch (Exception ex) 
     { 
      url = @"~/Error.aspx?err=" + Server.UrlEncode(ex.Message) + "&src=" + Server.UrlEncode(ex.StackTrace); 
     } 
     finally 
     { 
      conn.Close(); 
     } 
} 

if (url != "") { 
    Response.Redirect(url); 
} 
else { 
    // Page logic can continue 
} 
+0

thanx ..工作.. – anay 2009-11-30 14:26:47

0

使用變量來跟蹤內部try ... catch中何時發生錯誤,然後通過用if語句包圍Response.Redirect來檢查第二個錯誤。

0

每當您在try-catch塊內使用Response.Redirect時,您應該添加第二個參數。

取而代之的是:

Response.Redirect("somepage.aspx"); 

這樣做:

Response.Redirect("somepage.aspx", false); 

當該布爾值爲true,頁面內容被髮送到新的頁面(所以你可以使用表單值)。 當該布爾值爲false時,不會發送頁面內容。這可能是你想要的。你會知道你是否需要真實。

另一種方法是捕獲空的Catch塊中的ThreadAbortException。

1

考慮的第一反應

if (url != "") { Response.Redirect(url);} 

更改代碼
if (!string.IsNullOrEmpty(url)) { Response.Redirect(url);}