2014-03-01 34 views
1

我想實現類似於我的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聲明。

+0

試圖抓住一個const char *參數: http://stackoverflow.com/questions/2410609/c-exception-parameter – Lovy

回答

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; 
    } 
} 
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; 
    } 
} 
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 ... 
} 
相關問題