我有以下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
发送回客户端?
答案 0 :(得分:2)
使用try / catch语句包围它
try
{
string Connectioncacha = "";
CacheConnection CacheConnect = new CacheConnection();
CacheConnect.ConnectionString = Connectioncacha;
CacheConnect.Open();
}
catch (Exception e)
{
if (CacheConnect)
CacheConnect.Close();
}