如何检查CacheConnection是否失败

时间:2014-12-02 18:52:27

标签: c# sql

我有以下C#:

string Connectioncacha = "";

CacheConnection CacheConnect = new CacheConnection();
CacheConnect.ConnectionString = Connectioncacha;
CacheConnect.Open();

if (CacheConnect.State == ConnectionState.Open)
{
    return "working";
}
else
{
    return "no data";
}

问题是,如果连接失败,它会在CacheConnect.Open()失败并抛出错误。

如何修改代码,以防万一连接失败,而不是显示页面错误,它只是将文本no data发送回客户端?

1 个答案:

答案 0 :(得分:2)

使用try / catch语句包围它

    try 
    {
      string Connectioncacha = "";

      CacheConnection CacheConnect = new CacheConnection();
      CacheConnect.ConnectionString = Connectioncacha;
      CacheConnect.Open();

    } 
    catch (Exception e)
    {

       if (CacheConnect)
           CacheConnect.Close();
    }