我将 Qt Creator 用于一个项目,我想在我的 Qt 代码中处理多个异常。当发生错误时,我想在 QMessageBox::critical() 中显示它。
为此,我创建了一个 myExceptions.h 类,如下所示:
#ifndef MYEXCEPTIONS_H
#define MYEXCEPTIONS_H
#include <iostream>
#include <exception>
using namespace std;
class myExceptions : public runtime_error
{
private:
char err_msg;
public:
myExceptions(const char *msg) : err_msg(msg){};
~myExceptions() throw();
const char *what () const throw () {return this->err_msg.c_str();};
};
#endif // MYEXCEPTIONS_H
我以这种方式在我的代码中调用异常:
abc.cpp
if (!MyClass::aMethod(a, b) )
{
//setmessage of my exception
throw myExceptions("Error message to show");
}
并在我的 main.cpp 中捕获它:
try {
MyClass2 myClass2(param);
} catch (const char &e) {
QMessageBox::critical(&window, "title", e.what());
}
当我这样做时,我遇到了一些错误:
C2512: 'std::runtime_error': no appropriate default constructor available
C2440: 'initializing' : cannot convert from 'const char*' in 'char'
C2439: 'myExceptions::err_msg': member could not be initialized
C2228: left of '.c_str' must have class/struct/union
C2228: left of '.what' must have class/struct/union
有人能帮我吗?先感谢您!