抛出异常并返回函数的结果
Throw exception and return result from a function
我只是在学习C++,想抛出一个异常,但我的函数结果会是未定义的???
std::vector<myStruct> extract_notworking(std::vector<myStruct>& avec){
std::vector<myStruct> result;
if (avec.size() == 0)
//throw domain_error("Cannot operate on empty vector!");
//Cannot use exception for it would yield undefined result
return result;
//do something here
//...
return result;
}
我该怎么办?是否返回空矢量?如果我将异常抛出给返回值的接收器,会发生什么?
当抛出异常时,函数会在那里停止,执行会跳到捕捉到异常的位置。您的函数不返回任何内容,因为该函数根本不返回。
你可以直接做
if (avec.empty())
throw domain_error("Cannot operate on empty vector!");
您的函数将从那里退出。
请注意,您不需要关心返回值("一个函数怎么能不返回任何东西?"等),因为即使您尝试,也无法访问抛出(且未捕获)异常的函数的返回值。
例如,如果你做
try {
std::vector<myStruct> vec;
std::vector<myStruct> retval = extract_notworking(vec);
print_vector(retval); // this line is only executed if extract_networking
// does not throw an exception
} catch (const domain_error& e) {
// we can't access retval here so no worries
}
只有当函数正确返回(即不抛出)时,才能访问retval
。在本例中,函数将抛出,因为vec
为空,因此永远不会调用print_vector
。
即使你这样做:
std::vector<myStruct> retval;
try {
std::vector<myStruct> vec;
retval = extract_notworking(vec);
print_vector(retval);
} catch (const domain_error& e) {
// we can access retval here but the assignment never happened
}
由于函数没有返回,因此没有将其返回值分配给retval
,并且retval
仍然是一个完全正常的默认构造的vector
,您可以自由使用。因此,在该示例中,retval
没有被分配,retval
也没有被打印,因为extract_networking
抛出了一个异常,在这两件事发生之前,执行就跳到了catch
块中。
当您throw
是一个异常时,您不能return
,反之亦然。您可以将异常视为针对异常情况和错误而设计的通用return
。考虑这个功能:
int f(bool b) {
if (b)
return 42;
throw std::runtime_error("Runtime error!");
}
当我们调用它时,我们可以在表达式中捕获它的正常返回值(在本例中为int
),或者我们可以使用具有正确类型的catch
的try
块捕获它的异常返回值(std::runtime_error
):
try {
int normal_result = f(b);
// Use normal result.
// (Exceptional result does not exist.)
std::cout << normal_result << 'n';
} catch (const std::exception& exceptional_result) {
// Use exceptional result.
// (Normal result does not exist.)
std::cout << exceptional_result.what() << 'n';
}
当然,异常的威力来自于这样一个事实,即它们在调用堆栈中向上传播,直到达到匹配的catch
。因此,您可以使用它们来逃离深度嵌套的函数调用,同时确保您的资源(内存、文件和c)得到正确管理。
我该怎么办?是否返回空矢量?如果我将异常抛出给返回值的接收器,会发生什么?
函数返回的内容无关紧要,因为返回值不会以任何方式使用。执行将在该特定异常的下一个catch处继续(在展开堆栈后偏离路线)。
- 在没有定义返回类型的函数中返回布尔值,并将结果保存在无错误的char编译中-为什么
- C++Brute Force攻击函数不会返回结果
- 如何从递归函数中完全返回,该函数给出了每个函数结果的累积相加?
- C++ SSE 内部函数:将结果存储在变量中
- c++ lambda:柯里和函数:使用按值捕获与按引用捕获返回不同的结果
- C++ 随机数生成器:尝试将结果作为向量获取,但通过制作 void 函数来执行此操作而出现错误
- C++ 获取函数在常量引用中按值返回的结果
- C++ 犰狳库中的sort_index()函数给出了错误的结果
- 从返回 std::optional of std::vector 的函数中获取结果到调用方
- 类中静态函数C++意外结果
- 为什么函数 tellg() 没有返回好的结果?
- 模板函数意外的结果
- 使用具有默认参数的函数模板进行 decltype 会使结果混乱(一个有趣的问题或 gcc 的错误)
- lambda 函数未显示正确的结果
- 为什么我可以改变常量对象中的成员变量,这是返回常量对象函数的结果?
- 我们如何并行运行算法的 n 个实例并以有效的方式计算结果函数的平均值?
- Fmod 函数清楚地输出一个预期的双精度值,但 if(fmod == 预期的双精度值)的计算结果不是 true
- 有没有办法将 for 循环结果返回到像三元运算符这样的函数中?
- 为什么这个涉及 std::enable_if 的模板元函数会产生不希望的结果?
- 使用类似的比较函数时,在 c++ 中为 std:sort 获得不同的结果