問題描述
可能的重復:
在 C++ 中通過指針捕獲異常
我總是按值捕獲異常.例如
I always catch exceptions by value. e.g
try{
...
}
catch(CustomException e){
...
}
但我遇到了一些用 catch(CustomException &e)
代替的代碼.這是 a) 好的 b) 錯誤的 c) 灰色區(qū)域嗎?
But I came across some code that instead had catch(CustomException &e)
instead. Is this a)fine b)wrong c)a grey area?
推薦答案
C++ 中異常的標準做法是......
The standard practice for exceptions in C++ is ...
按值拋出,按引用捕獲
在繼承層次結構面前,按值捕獲是有問題的.假設對于您的示例,還有另一種類型 MyException
繼承自 CustomException
并覆蓋錯誤代碼等項目.如果拋出 MyException
類型,您的 catch 塊將導致它被轉換為一個 CustomException
實例,這將導致錯誤代碼發(fā)生變化.
Catching by value is problematic in the face of inheritance hierarchies. Suppose for your example that there is another type MyException
which inherits from CustomException
and overrides items like an error code. If a MyException
type was thrown your catch block would cause it to be converted to a CustomException
instance which would cause the error code to change.
這篇關于C++ catch 塊 - 按值或引用捕獲異常?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!