Question

I'm trying to implement something similar to the following in my VS 2008 C++/MFC project:

class myClass()
{
public:
    myClass()
    {
        //Do work... check for errors
        if(var < 0)
        {
            //Error
            TCHAR buff[1024];
            _snwprintf_s(buff, SIZEOF(buff), L"ERROR: The value of var=%d", var);
            throw buff;
        }
    }
};

__try
{
    //Begin using class above
    //The class member may be also defined on the global scale, thus
    //the following exception trap may happen via SetUnhandledExceptionFilter

    myClass mc;
}
__except(1)
{
    //Process unhandled exception
    //But how to trap the string passed in 'throw' above?
}

But I can't seem to catch the "string" that I'm passing in the throw statement.

No correct solution

OTHER TIPS

Use std::runtime_error, eg:

#include <stdexcept>

class myClass()
{
public:
    myClass()
    {
        //Do work...check for errors
        if(var < 0)
        {
            //Error
            char buff[1024];
            _snprintf_s(buff, SIZEOF(buff), "ERROR: The value of var=%d", var);
            throw std::runtime_error(buff);
        }
    }
};

try
{
    //Begin using class above
    myClass mc;
}
catch (const std::runtime_error &e)
{
    //Process unhandled exception
    //e.what() will return the string message ...
}

You can try something like this, for example:

struct CustomError {
    CustomError(std::string& info)
        : m_info(info) {}
    std::string m_info;
};

/*...*/
int main() {
    try {
        std::string info = "yo dawg";
        throw CustomError(info);
    }
    catch (CustomError& err) {
        std::cout << "Error:" << err.m_info;
    }
}

Character buffer way:

#include <string>
#include <iostream>

void DoSomething()
{
   throw "An error occurred!";
}

int main()
{
   try
   {
      DoSomething();
      std::cout << "Nothing bad happened" << std:endl;
   }
   catch(const char &err)
   {
      std::cerr << err << std::endl;
   }
}

, or std::string way:

#include <string>
#include <iostream>

void DoSomething()
{
   throw std::string("An error occurred!");
}

int main()
{
   try
   {
      DoSomething();
      std::cout << "Nothing bad happened" << std:endl;
   }
   catch(std::string &err)
   {
      std::cerr << err << std::endl;
   }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top