gpt4 book ai didi

language-agnostic - 检查错误的首选方式

转载 作者:行者123 更新时间:2023-12-03 07:46:24 25 4
gpt4 key购买 nike

如果我想说的话,请检查int是否在两个特定数字之间,最好将其实现为无异常(exception),例如:

int a; //example in C++, but translate into your language of choice...
cin >> a;
if(a < 0 || a > 5)
cout << "You must enter in a number between 0 and 5 inclusive!" << endl;

还是try-catch块中有异常?
try
{
int a;
cin >> a;
if(a < 0 || a > 5)
throw "You must enter in a number between 0 and 5 inclusive!" << endl;
}
catch(string msg)
{
cout << msg << endl;
}

最佳答案

“更好”也不是。如何处理异常情况,错误等,完全取决于确切的情况和代码的设计。当错误导致以下代码被跳过时,try-catch块非常有用。另一方面,当您想让用户知道问题但无论如何继续进行操作(例如,假设为默认值)时,try-catch可能不合适。

此外,某些程序还设计有自定义错误处理代码,以便可以记录和记录错误和异常,并确保程序可以正常运行。如果您使用的是这种系统,则可能根本不使用“throw”,而是使用类似
ErrorHandler.logError(“出问题了!”);

关于language-agnostic - 检查错误的首选方式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4319914/

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