尝试Catch不能解决sql连接错误 [英] Try Catch not working on sql connection error
问题描述
请帮助我,我试图在sql server连接失败时捕获错误。
这是一个例子
Hi,
Please help me, I am trying to catch the error when the connection fails in sql server.
Here's the example
SqlConnection sqlConnectLocal;
DataTable dt = new DataTable();
string strConString = string.Empty;
dt = new DataTable();
try
{
sqlConnectLocal = webConnectServer(strConString);
SqlCommand cmd = new SqlCommand(strQuery, sqlConnectLocal);
SqlDataAdapter sqlda = new SqlDataAdapter(cmd);
sqlda.SelectCommand.CommandTimeout = 30;
sqlda.Fill(dt);
}
catch (SqlException ex)
{
}
现在,它应该输入catch语句,因为我故意使我的连接字符串错误,因为我想测试我的程序是否可以捕获sql连接错误。
但它停止处理而没有任何反应。没有错误显示它只是停止
我怎么能发现这个错误。
谢谢
Now, it should enter the catch statement because I intentionally made my connection string wrong because I want to test if my program can catch the sql connection error.
But instead it stop processing and nothing happen. No error showed it just stop
How can I catch this error.
Thank you
推荐答案
没有错误显示它只是停止
No error showed it just stop
当然它没有显示错误:你的 catch
块是空的!因为您的代码引发了 SqlException
,所以执行 catch
块中的代码。但是 catch
块中没有代码!
试试这个:
Of course it doesn't show an error: your catch
block is empty! Because your code raised a SqlException
, the code into your catch
block gets executed. But there's no code in the catch
block!
Try this:
catch (SqlException ex)
{
Response.Write(String.Format("SqlException: {0}",ex.Message));
}
catch (Exception ex)
{
Response.Write(String.Format("Exception: {0}", ex.Message));
}
finally
{
if (sqlConnectLocal != null)
{
sqlConnectLocal.Close();
}
}
我还关闭了 finally
块中的连接,因为它是重要的是连接关闭。
还要加第二个 catch
阻止,因为如果异常不是 SqlException
,它会自动跳转到 finally $如果你没有添加
catch(Exception ex){...}
块,则c $ c>阻止。
希望这有帮助。
I also closed the connection in a finally
block, because it's important that the connection gets closed.
Also add a second catch
block, because if the exception isn't a SqlException
, it jumps automatically to the finally
block if you don't add a catch (Exception ex) { ... }
block.
Hope this helps.
这篇关于尝试Catch不能解决sql连接错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!