-1

所以我在 c# 中有以下字符串,它返回一个 mysql 查询。

string id = cmd.ExecuteScalar().ToString();

问题是如果这个字符串的输入无效,它会使应用程序崩溃。这不应该使应用程序崩溃,而是显示:

MessageBox.Show("Your key (" + KeyNr + ") was invalid or not active. \nPlease check if it is the correct key or you need to buy another month.", "Login Error", MessageBoxButtons.OK, MessageBoxIcon.Error);

尝试尝试并没有运气。有人可以帮忙吗?

我的一些尝试:

try
{
   string id = cmd.ExecuteScalar().ToString();
}
catch (Exception ex)
{
   MessageBox.Show("Your key (" + KeyNr + ") was invalid or not active. \nPlease check if it is the correct key or you need to buy another month.", "Login Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}

try
{
   string id = cmd.ExecuteScalar().ToString();
}
catch (catch (MySqlException))
{
   MessageBox.Show("Your key (" + KeyNr + ") was invalid or not active. \nPlease check if it is the correct key or you need to buy another month.", "Login Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}

一切都给了我:

Error   2   The name 'id' does not exist in the current context
4

2 回答 2

4

在不为您解决的情况下,您需要cmd.ExecuteScalar()在假设它执行并可以转换为字符串之前存储并检查结果。

var result = cmd.ExecuteScalar();
if (/* result is valid */){
  id = result.ToString();
} else {
  MessageBox.Show(/* message */);
}

尽可能远离异常检查,因为使用它们会不必要地增加性能,并且(在很多方面)是一种跳过良好老式检查的懒惰方式。

于 2012-10-28T18:43:26.187 回答
0

试试这段代码:

string id = string.Empty;

try
{
   id = cmd.ExecuteScalar().ToString();
}
catch(Exception ex)
{
    MessageBox.Show("Your key (" + KeyNr + ") was invalid or not active. \nPlease check if it is the correct key or you need to buy another month.", "Login Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}

您甚至可以将其捕获到更具体的 Exception 而不是 generic Exception

于 2012-10-28T18:42:26.923 回答