86_C++_异常捕获_catch(const string str){cout<<str<<endl;}catch(const char*str){cout<<str<<endl;}区别

这两种 catch 语句的主要区别在于它们捕获的异常类型和传递的参数类型。

  1. catch(const string str):

    • 这个捕获块用于捕获类型为 std::string 的异常。
    • 在这种情况下,抛出的异常必须是一个 std::string 对象。
    • 捕获到的异常会被复制到 str,因此发生了一个对象的拷贝。
  2. 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,这样可以避免不必要的拷贝操作。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值