C++ catch 块 - 按值或引用捕获异常?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2522299/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 23:47:25  来源:igfitidea点击:

C++ catch blocks - catch exception by value or reference?

c++exception-handling

提问by Mr. Boy

Possible Duplicate:
catch exception by pointer in C++

可能的重复:
在 C++ 中通过指针捕获异常

I always catch exceptions by value. e.g

我总是按值捕获异常。例如

try{
...
}
catch(CustomException e){
...
}

But I came across some code that instead had catch(CustomException &e)instead. Is this a)fine b)wrong c)a grey area?

但是我遇到了一些相反的代码catch(CustomException &e)。这是 a) 好的 b) 错误的 c) 灰色区域吗?

回答by JaredPar

The standard practice for exceptions in C++ is ...

C++ 中异常的标准做法是...

Throw by value, catch by reference

按值抛出,按引用捕获

Catching by value is problematic in the face of inheritance hierarchies. Suppose for your example that there is another type MyExceptionwhich inherits from CustomExceptionand overrides items like an error code. If a MyExceptiontype was thrown your catch block would cause it to be converted to a CustomExceptioninstance which would cause the error code to change.

面对继承层次结构,按值捕获是有问题的。假设对于您的示例,还有另一种类型MyException继承CustomException并覆盖了诸如错误代码之类的项目。如果MyException抛出一个类型,您的 catch 块会导致它被转换为一个CustomException实例,这会导致错误代码发生变化。

回答by CB Bailey

Catching by value will slicethe exception object if the exception is of a derived type to the type which you catch.

如果异常是您捕获的类型的派生类型,则按值捕获将对异常对象进行切片

This may or may not matter for the logic in your catch block, but there is little reason not to catch by const reference.

这对于 catch 块中的逻辑可能重要也可能无关紧要,但没有理由不通过 const 引用进行捕获。

Note that if you throw;without a parameter in a catch block, the original exception is rethrown whether or not you caught a sliced copy or a reference to the exception object.

请注意,如果您throw;在 catch 块中没有参数,则无论您是否捕获了切片副本或对异常对象的引用,都会重新抛出原始异常。

回答by Marcelo Cantos

Unless you want to fiddle with the exception, you should usually use a const reference: catch (const CustomException& e) { ... }. The compiler deals with the thrown object's lifetime.

除非您想处理异常,否则通常应该使用 const 引用:catch (const CustomException& e) { ... }. 编译器处理抛出对象的生命周期。

回答by Mihir Mehta

in (CustomException e)new object of CustomException is created... so it's constructor will be called while in (CustomException &e) it will just the reference... not new object is created and no constructor will be called... so formal is little bit overhead... later is better to use...

(CustomException e)CustomException 的新对象中创建......所以它的构造函数将被调用,而在 (CustomException &e) 中它只会引用......没有创建新对象并且不会调用任何构造函数......所以正式是有点开销……以后用比较好……