1

我将 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

有人能帮我吗?先感谢您!

4

2 回答 2

4

我认为您没有正确构造 runtime_error 您的自定义异常类派生自。您需要简单地执行以下操作:

class myExceptions : public runtime_error
{
public:
    myExceptions(const char *msg) : runtime_error(msg) {};
    ~myExceptions() throw();
};

你不需要实现 what() 函数,因为它已经在 runtime_error 类中实现了。我还将捕获特定的异常类型:

try {
    MyClass2 myClass2(param);
} catch (const myExceptions &e) {
    QMessageBox::critical(&window, "title", e.what());
}
于 2014-03-11T15:00:15.237 回答
1

You are trying to initialize a char variable, your err_msg member of the myExceptions class, with a C-string value (msg).

You need to copy the message to your exception class or, at least, save its pointer (and make sure it will be in scope and won't change until your message box is shown).

于 2014-03-11T14:55:13.667 回答