首页 > 解决方案 > 在 C++ 中发生任何异常时运行通用代码

问题描述

我看起来类似于finallyc++ 但我遇到了RAII。不过,我有一点困惑。如果我有一些通用代码我想在出现任何异常的情况下运行,

例子: std::cout << "exception occured" << std::endl;

有没有办法做到这一点而不是复制相同的代码?

#include <iostream>

int main()
{
    bool firstException = false;
    try
    {
        if(firstException)
            throw std::invalid_argument("the truth is out there!!");
        else
            throw std::domain_error("Bazzinga");
    }
    catch (std::invalid_argument const& e)
    {
        std::cout << e.what() << std::endl;
        std::cout << "exception occured" << std::endl;
    }
    catch (std::domain_error const& e)
    {
        std::cout << e.what() << std::endl;
        std::cout << "exception occured" << std::endl;
    }
}

标签: c++exception

解决方案


我现在明白了molbdnilo在评论中所说的内容。下面的代码有答案。:) :D

#include <iostream>

int main()
{
    bool firstException = true;
    try
    {
        if(firstException)
            throw std::invalid_argument("the truth is out there!!");
        else
            throw std::invalid_argument("Bazzinga");
    }
    catch (std::exception const& e)
    {
        std::cout << e.what() << std::endl;
        std::cout << "exception occured" << std::endl;
    }
}

推荐阅读