2013-03-14 99 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