你可以/应该在 ac# switch 语句中抛出异常吗?

发布于 2024-08-30 02:31:49 字数 835 浏览 14 评论 0原文

我有一个返回 int 的插入查询。基于该 int 我可能希望抛出一个异常。这适合在 switch 语句中执行吗?

 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;
        }

我通常在开关中添加break语句,但它们不会被击中。这是一个糟糕的设计吗?请与我分享任何意见/建议。

谢谢, ~ck 在圣地亚哥

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(8

乜一 2024-09-06 02:31:49

为什么不呢?

来自 Anders Hejlsberg 等人的《C# 编程语言,第三版》,第 362 页:

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

开关(i) {
案例0:
    while(true) F();
案例1:
    抛出新的 ArgumentException();
案例2:
    返回;
}

Why not?

From The C# Programming Language, Third Ed. by Anders Hejlsberg et al, page 362:

The statement list of a switch section typically ends in a break, goto case, or goto default statement, but any construct that renders the end point of the statement list unreachable is permitted. [...] Likewise, a throw or return statement always transfers control elsewhere and never reaches its end point. Thus the following example is valid:

switch(i) {
case 0:
    while(true) F();
case 1:
    throw new ArgumentException();
case 2:
    return;
}
樱花坊 2024-09-06 02:31:49

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

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

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} 等选择适当的参数。

No problem... why would this be bad design?

Alternatively, since the exception type is the same in all cases, you could construct a lookup table for the error messages. That would save you some code duplication. For example:

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));
}

In the messages themselves, you can select the appropriate parameter with {0}, {1}, etc.

來不及說愛妳 2024-09-06 02:31:49

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

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

I don't really agree with your variable naming conventions ;), but I don't see why what you did would be inappropriate. It seems like a fairly elegant way of translating an error from one medium to another.

I'm assuming that your "insert query" is some form of stored proc.

荭秂 2024-09-06 02:31:49

如果可能的话,如果您在设置失败结果的地方抛出,可能会更好,否则您最终必须同时进行结果检查和抛出。但当然可能不可能。

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

If possible it would probably be better if you threw wherever the failed result is set, otherwise you end up with having to do both result checking and throwing. But might not be possible of course.

Also, I'd make your error strings into resources or constants with placeholders so that you don't have to change multiple places if you want to change the wording.

凌乱心跳 2024-09-06 02:31:49

我认为这还可以。看起来您正在使用 switch 语句将返回代码映射到异常。只要病例不是太多,这不是问题。

I think this is OK. It seems like you are mapping an return code to an exception, using a switch statement. As long as there are not too many cases, this is not a problem.

橘虞初梦 2024-09-06 02:31:49

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

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

I don't see any issue with using a switch in your case.

The stronger consideration should go to whether exceptions themselves are appropriate. Generally, exceptions should be used only when a situation arises that is outside the bounds of expected behavior. Exceptions shouldn't be used as program flow logic. In your case you're probably okay to use them based on the code I see.

西瑶 2024-09-06 02:31:49

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

Dictionary<Result_Type, Exception>

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

There is nothing wrong with the approach you are taking. Switch statements are a lot easier to read than if/then statements (and potentially faster too). The other thing you could do is load the possible exceptions in a

Dictionary<Result_Type, Exception>

and pull the exception from there. If you have lots of switch statements this would make the code more compact (and you can add and remove them at runtime if you need to).

往事随风而去 2024-09-06 02:31:49

也许我请求与这里的所有答案不同。

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

我的代码看起来像:

throw new ClientException(result, cTbx.Text);

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

Maybe I beg to differ from all the answers here..

Instead of having to switch in the code, I would rather pass in the result to the ClientException class & let it decide what string it needs to show rather then have an ugly switch all over the place to create various messages

My code would look like:

throw new ClientException(result, cTbx.Text);

So, even if you can throw errors in switch...case, you can avoid it all is my take

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文