如果有错误,则进行切换与“良好”切换。案件
我对机器代码不太熟悉,但我认为这是一个非常简单的问题。
如果我想通过从函数返回的整数(而不是抛出异常的函数)进行错误处理,从机器代码的角度来看,更好的做法是:
- 检查条件语句中的整数是否为“坏”值,然后使用 switch 语句来处理“坏”值,或者
- 切换整数,并提供“好”值和“坏”值的情况
例如,在 C++ 中:
enum error_code {E_GOOD, E_BAD, E_UGLY};
error_code func_b();
选项 1
void func_a()
{
error_code err_catch = func_b();
if (err_catch)
{
switch (err_catch)
{
case E_BAD:
/* Handle bad case */
break;
case E_UGLY:
/* Handle ugly case */
break;
}
}
}
选项 2
void func_a()
{
error_code err_catch = func_b();
switch (err_catch)
{
case E_GOOD:
break;
case E_BAD:
/* Handle bad case */
break;
case E_UGLY:
/* Handle ugly case */
break;
}
}
感谢您的帮助。
I'm not very familiar with machine code, but I think this is a pretty simple question.
If I want to do error handling via an integer returned from a function (as opposed to the function throwing an exception), is it better practice—from a machine code standpoint—to:
- Check the integer in a conditional statement for a "bad" value, and then use a switch statement to handle the "bad" value(s), or
- Switch the integer, and provide a case for the "good" value(s) as well as the "bad" value(s)
For example, in C++:
enum error_code {E_GOOD, E_BAD, E_UGLY};
error_code func_b();
Option 1
void func_a()
{
error_code err_catch = func_b();
if (err_catch)
{
switch (err_catch)
{
case E_BAD:
/* Handle bad case */
break;
case E_UGLY:
/* Handle ugly case */
break;
}
}
}
Option 2
void func_a()
{
error_code err_catch = func_b();
switch (err_catch)
{
case E_GOOD:
break;
case E_BAD:
/* Handle bad case */
break;
case E_UGLY:
/* Handle ugly case */
break;
}
}
Thank you for your help.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
第一个测试可能应该是:
明确“发生错误”。顺便说一句,您的代码看起来像是正在通过 C++ 编译器。 C 不会使用前面的
enum
创建类型error_code
;您必须添加:就生成的代码而言,两者之间几乎没有什么区别。
我可能会使用选项 1(
if
表示法)只是为了明确开关仅处理错误情况(因为它只需要处理错误情况),但我不会反对要么是提交给我进行代码审查。The first test should probably be:
It is explicit about 'an error occurred'. Incidentally, your code looks like is passing through a C++ compiler. C does not create a type
error_code
with the precedingenum
; you would have to add:There will be very little difference between the two in terms of generated code.
I would probably use Option 1 (the
if
notation) simply to make it clear that the switch only deals with error cases (because it only has to deal with error cases), but I wouldn't object to either if it was presented to me for code review.对于
enum
类型,我会直接使用switch
语句,以便编译器可以确保switch
语句确实处理所有可能的值。With
enum
types, I would directly use aswitch
statement so that the compiler can make sure theswitch
statement really handles all possible values.