9

I have an insert query that returns an int. Based on that int I may wish to throw an exception. Is this appropriate to do within a switch statement?

 switch (result)
        {

            case D_USER_NOT_FOUND:
                throw new ClientException(string.Format("D User Name: {0} , was not found.", dTbx.Text));
            case C_USER_NOT_FOUND:
                throw new ClientException(string.Format("C User Name: {0} , was not found.", cTbx.Text));
            case D_USER_ALREADY_MAPPED:
                throw new ClientException(string.Format("D User Name: {0} , is already mapped.", dTbx.Text));
            case C_USER_ALREADY_MAPPED:
                throw new ClientException(string.Format("C User Name: {0} , is already mapped.", cTbx.Text));
            default:

                break;
        }

I normally add break statements to switches but they will not be hit. Is this a bad design? Please share any opinions/suggestions with me.

Thanks, ~ck in San Diego

4

8 回答 8

12

为什么不?

来自C# 编程语言,第三版。Anders Hejlsberg 等人着,第 362 页:

switch 部分的语句列表通常以breakgoto casegoto default语句结尾,但任何使语句列表的端点无法到达的构造都是允许的。[...] 同样,throworreturn语句总是将控制权转移到其他地方,并且永远不会到达终点。因此下面的例子是有效的:

switch(i) {
case 0:
    while(true) F();
case 1:
    throw new ArgumentException();
case 2:
    return;
}
于 2010-04-22T18:22:11.907 回答
4

没问题...为什么这是糟糕的设计?

或者,由于所有 s 中的异常类型相同case,您可以为错误消息构建一个查找表。这将为您节省一些代码重复。例如:

static private Dictionary<int, string> errorMessages;
static
{
    // create and fill the Dictionary
}

// meanwhile, elsewhere in the code...
if (result is not ok) {
    throw new ClientException(string.Format(errorMessages[result], cTbx.Text, dTbx.Text));
}

在消息本身中,您可以使用 、 等选择适当的{0}参数{1}

于 2010-04-22T18:19:27.867 回答
3

我真的不同意您的变量命名约定;),但我不明白为什么您所做的不合适。这似乎是一种将错误从一种媒介转换为另一种媒介的相当优雅的方式。

我假设您的“插入查询”是某种形式的存储过程。

于 2010-04-22T18:17:28.073 回答
1

如果可能的话,如果你在设置失败结果的地方投掷可能会更好,否则你最终不得不同时进行结果检查和投掷。但当然不可能。

此外,我会将您的错误字符串转换为带有占位符的资源或常量,这样如果您想更改措辞,您就不必更改多个位置。

于 2010-04-22T18:18:31.773 回答
0

也许我希望与这里的所有答案有所不同..

不必切换代码,我宁愿将 传递resultClientException类并让它决定它需要显示的字符串,而不是到处都有一个丑陋的开关来创建各种消息

我的代码看起来像:

throw new ClientException(result, cTbx.Text);

所以,即使你可以抛出错误switch...case,你也可以避免这一切都是我的看法

于 2010-04-22T18:43:57.657 回答
0

我认为在您的情况下使用开关没有任何问题。

更强烈的考虑应该是例外本身是否合适。通常,仅当出现超出预期行为范围的情况时才应使用异常。不应将异常用作程序流逻辑。在您的情况下,您可能可以根据我看到的代码使用它们。

于 2010-04-22T18:24:56.203 回答
0

我认为这没关系。似乎您正在使用 switch 语句将返回码映射到异常。只要没有太多的情况,这不是问题。

于 2010-04-22T18:18:17.680 回答
0

您采用的方法没有任何问题。Switch 语句比 if/then 语句更容易阅读(也可能更快)。您可以做的另一件事是将可能的异常加载到

Dictionary<Result_Type, Exception>

并从那里拉出异常。如果您有很多 switch 语句,这将使代码更紧凑(如果需要,您可以在运行时添加和删除它们)。

于 2010-04-22T18:19:53.263 回答