【问题标题】:Customize exceptions by showing error message C++ and Qt通过显示错误消息 C++ 和 Qt 自定义异常
【发布时间】:2014-03-11 14:49:41
【问题描述】:

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

有人可以帮助我吗?提前谢谢!

【问题讨论】:

  • 你抓错了类型

标签: c++ qt exception qt-creator qmessagebox


【解决方案1】:

我认为你没有正确构造你的自定义异常类派生的 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());
}

【讨论】:

  • 在 ~myExceptions() throw() 之后我添加了这样的大括号: ~myExceptions() throw() { } 然后它就可以工作了!
【解决方案2】:

您正尝试使用 C 字符串值 (msg) 初始化 char 变量,即 myExceptions 类的 err_msg 成员。

您需要将消息复制到您的异常类,或者至少保存它的指针(并确保它在范围内并且在显示消息框之前不会更改)。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-09-27
    • 2011-09-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多