为什么 throw() std::exception 引用存储来自 std::exception 的派生类对象抛出基类的异常而不是派生类 c++

问题描述 投票:0回答:1

好吧,伙计们,我失去了它。我花了很多时间,但无法找到线索。 我的测试程序如下:

#include <iostream>
#include <exception>

class   SyntaxErrorException : public std::exception
{
    public:
        const char* what() const throw()
        {
            return ("SyntaxErrorException thrown");
        }
};

int main(void)
{
    SyntaxErrorException    s;
    std::exception&         e1 = s;
    std::exception&         e2 = e1;

    try
    {
        throw (s);
    }
    catch(const std::exception& e)
    {
        std::cerr << "Error: " << e.what() << '\n';
    }
    try
    {
        throw (e1);
    }
    catch(std::exception& e)
    {
        std::cerr << "Error: " << e.what() << '\n';
    }
    try
    {
        throw (e2);
    }
    catch(const std::exception& e)
    {
        std::cerr << "Error: " << e.what() << '\n';
    }
    return (0);
}

其输出是:

Error: SyntaxErrorException thrown
Error: std::exception
Error: std::exception

我知道的一件事是,在e1e2两种情况下,这是关于切片问题。但为什么以及如何呢? 有没有人帮助我理解“抛出表达式”行中到底发生了什么,以便我得到一个基本的 std::Exception 抛出?

最终的情况是我想创建一个通用函数,它将 std::string 自定义错误消息和 std::Exception 引用作为参数索引要抛出的自定义异常。

为什么我不能通过引用将自定义异常类的对象传递给将抛出该异常的函数?还有其他办法吗?

谢谢你

c++ exception inheritance std
1个回答
0
投票

使用函数模板有效

#include <iostream>
#include <exception>

class SyntaxErrorException : public std::exception
{
public:
    const char* what() const throw()
    {
        return ("SyntaxErrorException thrown");
    }
};

template<typename T>
void throwException(T& e)
{
    throw e;
}

int main(void)
{
    try
    {
        SyntaxErrorException s;
        throwException(s);
    }
    catch(const std::exception& e)
    {
        std::cerr << "Error: " << e.what() << '\n';
    }
    return 0;
}

结果:

ERROR!
Error: SyntaxErrorException thrown
© www.soinside.com 2019 - 2024. All rights reserved.