[英]c# if-else within catch statement
我正在尝试在catch方法中编写一个if-else块,但是当我看到“并非所有代码路径都返回int类型”的错误时,
本质上,我正在编写一种将UserName和Password保存到Sql CE数据库的方法,并且我想测试一个特定的错误。 (UserName已经存在。)UserName列是唯一的,因此它将可靠地引发NativeError = 25016的SqlCeException。我想显示一条错误消息,否则将以更通用的方式处理其他异常。
我的代码是:
try
{
//insert command (This is where the duplicate column error is thrown)
//Select @@Identity & Return it
}
catch (SqlCeException ex)
{
if (ex.NativeError == 25016)
MessageBox.Show("Username already in use.");
else
//whatever
}
我尝试显示不同的,更通用的消息,并得到不返回错误。 我试图抛出一个新的异常并将其捕获到另一个块中。 同样的错误。 我尝试返回-1(作为一种标记值)。 同样的错误。
在这种特定情况下,似乎没有比SqlCeException更具体的错误(尽管我刚刚使我的debug-fu失败了)。
有任何创造性的解决方法吗? 最坏的情况是,我将编写一个方法,在调用该方法之前检查数据库是否存在重复的用户名。
看来您的方法返回一个int
。 您需要从catch块返回int
类型的值。
try
{
//insert command (This is where the duplicate column error is thrown)
//Select @@Identity & Return it
}
catch (SqlCeException ex)
{
if (ex.NativeError == 25016)
MessageBox.Show("Username already in use.");
else
{
//whatever
}
return -1;
}
听起来您的函数返回一个int
值。
在try
块中,您获取并返回一个整数值。 没关系。
在catch
块中,您不会提及返回整数。 这就是问题。
因此,当函数采用异常路径时,它没有返回值的整数会导致错误。
您的整个函数需要返回值。 由于您在try-cathc中正在吃异常,因此您需要在函数末尾返回某种返回值。
使用finally块返回int:
try
{
//insert command (This is where the duplicate column error is thrown)
//Select @@Identity & Return it
}
catch (SqlCeException ex)
{
if (ex.NativeError == 25016)
MessageBox.Show("Username already in use.");
else
//whatever
}
finally
{
return -1;
}
如果try块返回了Identity值,那么最终return -1
将无效。 参考
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.