1

I was looking similar to finally for c++ but I came across RAII. I have a small confusion though. If I have some common code I want to run in case of any exception,

Example: std::cout << "exception occured" << std::endl;

Is there a way to do that instead of copy the same code?

#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;
    }
}
raz
  • 482
  • 1
  • 5
  • 17
  • 2
    All standard exceptions are derived from `std::exception`. – molbdnilo Apr 29 '20 at 08:48
  • @molbdnilo `catch(std::exception const& e)` I have tried to add this at the end of catch list. But for the current example above, it never goes inside because for current exception there is a catch block explicitly for that. Could you please elaborate a bit how that will be helpful ?? – raz Apr 29 '20 at 09:06

1 Answers1

1

I got now what molbdnilo was talking about in the comment. The code below has the answer. :) :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 (const std::exception& e)
    {
        std::cout << e.what() << std::endl;
        std::cout << "exception occured" << std::endl;
    }
    catch (...)
    {
        std::cout << "will catch any exception occured" << std::endl;
    }
}
raz
  • 482
  • 1
  • 5
  • 17