使用自定义字符串参数捕获抛出异常

时间:2014-03-01 23:52:37

标签: c++ windows winapi exception mfc

我正在尝试在我的VS 2008 C ++ / MFC项目中实现类似于以下的内容:

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?
}

但我似乎无法抓住我在throw声明中传递的“字符串”。

3 个答案:

答案 0 :(得分:1)

使用std::runtime_error,例如:

#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 ...
}

答案 1 :(得分:0)

您可以尝试这样的事情,例如:

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;
    }
}

答案 2 :(得分:0)

字符缓冲方式:

#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;
   }
}

,或std::string方式:

#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;
   }
}