Pergunta

I use Qt Creator for a project and I would like to handle multiple exceptions in my Qt code. When an error occurs, I would like to show it in a QMessageBox::critical().

For that I created a class myExceptions.h as follow:

#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

I call an exception in my code in this way:

abc.cpp

if (!MyClass::aMethod(a, b) )
{
   //setmessage of my exception
  throw myExceptions("Error message to show");

 }

and catch it in my main.cpp:

 try {
        MyClass2 myClass2(param);
    } catch (const char &e) {
       QMessageBox::critical(&window, "title", e.what());
    }

When I do this, I got some errors:

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

Can someone help me? Thank you in advance!

Foi útil?

Solução

I think you do not properly construct runtime_error your custom exception class derived from. You need simple do the following:

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

You do not need to implement what() function, because it is already implemented in runtime_error class. I would also catch the specific exception type:

try {
    MyClass2 myClass2(param);
} catch (const myExceptions &e) {
    QMessageBox::critical(&window, "title", e.what());
}

Outras dicas

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).

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top