这两种 catch
语句的主要区别在于它们捕获的异常类型和传递的参数类型。
-
catch(const string str)
:- 这个捕获块用于捕获类型为
std::string
的异常。 - 在这种情况下,抛出的异常必须是一个
std::string
对象。 - 捕获到的异常会被复制到
str
,因此发生了一个对象的拷贝。
- 这个捕获块用于捕获类型为
-
catch(const char* str)
:- 这个捕获块用于捕获类型为 C 风格字符串(即以 null 结尾的字符数组)的异常。
- 抛出的异常必须是一个字符串字面量或
const char*
类型的指针。 - 捕获到的异常是一个指针,不会进行拷贝。
示例
#include <iostream>
#include <string>
void test() {
throw std::string("This is a string exception");
// throw "This is a C-style string exception"; // 也可以抛出这个
}
int main() {
try {
test();
} catch (const std::string& str) { // 使用引用避免拷贝
std::cout << "Caught string: " << str << std::endl;
} catch (const char* str) {
std::cout << "Caught C-style string: " << str << std::endl;
}
return 0;
}
总结
- 使用
catch(const string str)
时,你需要抛出一个std::string
对象,而使用catch(const char* str)
时,可以抛出 C 风格的字符串。 - 由于 C++ 的异常处理机制,通常推荐使用
const std::string&
来捕获std::string
,这样可以避免不必要的拷贝操作。