我的意思是,我知道所有关于 throw, try {} catch {} 的语言规则,但我不确定我在现实世界中是否正确使用它们。请看下面的例子:
我们有一大段科学代码可以进行各种图像处理,最近我们决定对其进行修饰并使其更加健壮。经常使用的例程之一是void rotate_in_place(float* image, image_size sz) ;
为了使它更健壮,我们在代码的开头添加了一些完整性检查:
void rotate_in_place(float* image, image_size sz) {
// rotate_in_place does not support non-square image;
if (sz.nx != sz.ny) throw NonSquareImageError;
// rotate_in_place does not support image too small or too large
if (sz.nx <= 2 || sz.nx > 1024) throw WrongImageSizeError;
// Real rode here
.....
}
现在的问题是,rotate_in_place() 被用在了 1000 多个地方,我是否应该用 try{} catch {} 包装每个 rotate_in_place() 调用,这在我看来会让代码非常臃肿。另一种可能性是不包装任何 try{} catch{} 并让程序退出,但这与仅使用有何不同
if (sz.nx != sz.ny) {
cerr << "Error: non-squared image error!\n";
exit(0);
}
简而言之,我不太确定使用 throw、try、catch 的真正好处,有什么好的建议吗?