多字符串异常处理

用户名

我想抛出多个(2)不同的字符串异常,并且希望它们被2个单独的catch捕获,如何做到这一点?

    try
    {
        std::istringstream ss2(argv[i]);

        if (!(ss2 >> l)) throw (std::string)"abc";
        if(l < 0 || l > n) throw (std::string)"xyz";
    }

    catch(std::string abc) {
        do something for abc
    }

    catch(std::string xyz){
        do something for xyz
    }

上面的代码将始终触发第一个捕获,而不会触发第二个捕获。

谢尔盖·卡里尼琴科(Sergey Kalinichenko)

catch子句确定要按类型捕获的异常,而不是按值或要捕获的异常对象的属性来捕获。

如果您想以不同的方式捕获这两个异常,则应该创建两个单独的异常类型,而不是抛出std::string

struct exception_one {
    std::string message;
    exception_one(const std::string& m) : message(m) {}
};
struct exception_two {
    std::string message;
    exception_two(const std::string& m) : message(m) {}
};
...
try {
    std::istringstream ss2(argv[i]);
    if (!(ss2 >> l)) throw exception_one("abc");
    if(l < 0 || l > n) throw exception_two("xyz");
}
catch(exception_one& abc) {
    do something for abc
}
catch(exception_two& xyz){
    do something for xyz
}

注意符号&catch子句:你按值抛出异常,并通过引用赶上他们

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章