简体   繁体   中英

Throwing a custom exception from a nested function C++

I have custom exception class below:

#include <exception>

#pragma once
class MyException : public std::exception
{
public:
    MyException ();
    MyException (std::string message="");
    virtual const char* what()throw();
private:
    std::string m_exceptionMessage;
};

The corresponding .cpp file has the right definitions.

Here is how my function is nested:

f1();
f2();
void main()
{
   try
   {
      f1();
   }

   catch (std::exception &ex)
   {
      std::cerr << ex.what() << std::endl;
   }
}

void f1()
{
   try
   {
      f2();
   }
   catch (std::exception &ex)
   {
      throw std::exception(ex);
   }
}

void f2()
{
   try
   {
      InitCalculations();
      hr = DoSomething();
      if(hr!=S_OK)
          throw MyException ("invalid argument")
   }
   catch (std::exception &ex)
   {
      throw std::exception(ex);
   }

}

I have tried to summarize the problem. All the functions lie in different files under different headers. I get the right message pass to the first catch in function f2() , however as I try to propagate this message, I lose it in f1() and hence in main() What is the right way to propagate the exception coming from f2() to the main() function?

throw std::exception(ex); creates a new exception object which is not MyException any more. That's why you lose the message. You need to use just throw; , it rethrows the existing caught exception.

And, btw. you shouldn't use std::string nor any other object which allocates from heap inside your exception. Program might have thrown exception because of not enough memory and std::string will then throw another one because it cannot allocate buffer, causing your program to exit.

Use const char * literal and if you need variable text use statically allocated char[] buffer and populate it with sprintf() .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM