scc*_*ccs 5 c++ error-handling if-statement
我的程序等待用户输入,并在适当时处理它.我需要检查用户输入以确保它符合某些标准,如果它不符合所有这些标准,它将被拒绝.
伪代码类似于:
if (fulfills_condition_1)
{
if (fulfills_condition_2)
{
if (fulfills_condition_3)
{
/*process message*/
}
else
cout << error_message_3; //where error_message_1 is a string detailing error
}
else
cout << error_message_2; //where error_message_2 is a string detailing error
}
else
cout << error_message_1; //where error_message_3 is a string detailing error
Run Code Online (Sandbox Code Playgroud)
这些条件的数量可能会增加,我想知道是否有一种更简洁的方式来表示使用开关或类似的东西而不是大量的级联if语句.
我知道有可能使用
if (fulfills_condition_1 && fulfills_condition_2 && fulfills_condition_3)
/*process message*/
else
error_message; //"this message is not formatted properly"
Run Code Online (Sandbox Code Playgroud)
但这没有第一个那么有用,也没有说明问题出在哪里.
这些条件可以粗略地安排得越来越重要,即检查condition_1比检查更重要condition_3,因此这些if语句确实有效 - 但是这样做有更好的方法吗?
怎么样
if (!fulfills_condition_1) throw BadInput(error_message_1);
if (!fulfills_condition_2) throw BadInput(error_message_2);
if (!fulfills_condition_3) throw BadInput(error_message_3);
/* process message */
Run Code Online (Sandbox Code Playgroud)
然后,您的异常处理程序可以报告错误消息,并根据需要重试或中止。
| 归档时间: |
|
| 查看次数: |
198 次 |
| 最近记录: |