2013-03-14 58 views
1

拋出我有這樣的代碼異常的頁面重定向在asp.net

protected void Button_Click(object sender, EventArgs e) 
{ 
    try 
    { 
     // some code 

     con.Open(); 
     string result = command.ExecuteScalar().ToString(); 

     if (result != string.Empty) 
     { 
      // some code 
      Response.Redirect("Default.aspx"); 
     } 
    } 
    catch (Exception ex) 
    { 
     throw new Exception(ex.Message); 
    } 
    finally 
    { 
     con.Close(); 
    } 

它提供了從Response.Redirect("Default.aspx");

前的異常:線程已被中止。

任何想法爲什麼?

感謝名單

+0

這似乎是一個重複的問題結帳[這](http://stackoverflow.com/questions/2777105/response-redirect-causes-system-threading-threadabortexception) – 2013-03-14 16:28:58

回答

2

從try ... catch語句中的重定向將導致這個異常被拋出,那麼這是不是你想要做什麼。

我會更新您的代碼;

string result = string.Empty; 

try 
{ 
    // some code 
    con.Open(); 
    result = command.ExecuteScalar().ToString();   
} 
catch (Exception ex) 
{ 
    throw new Exception(ex.Message); 
} 
finally 
{ 
    con.Close(); 
} 

if (result != string.Empty) 
{ 
    // some code 
    Response.Redirect("Default.aspx"); 
} 
+0

是的,這就是問題所在。 thanx – Darshana 2013-03-14 16:33:30

0

這是ASP.NET執行重定向時引發的典型異常。它在Interweb上有很好的記錄。

嘗試下面的catch塊來吞下異常,所有應該沒問題。它應該什麼都不做!

catch(ThreadAbortException) 
{ 
} 
catch (Exception ex) 
{ 
    throw new Exception(ex.Message); 
} 
finally 
{ 
    con.Close(); 
} 
+0

我會避免吞嚥異常 - 即使在這種情況下沒有明顯的副作用,進入IMO也是一個壞習慣。有更好的方法來處理它 - 例如Tim B James在下面回答。 – Tim 2013-03-14 16:29:36