gpt4 book ai didi

c# - 您可以/应该在 c# switch 语句中抛出异常吗?

转载 作者:太空狗 更新时间:2023-10-29 17:35:28 28 4
gpt4 key购买 nike

我有一个返回 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 在圣地亚哥

最佳答案

为什么不呢?

来自 The C# Programming Language, Third Ed.,Anders Hejlsberg 等人,第 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;
}

关于c# - 您可以/应该在 c# switch 语句中抛出异常吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2693308/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com