Search code examples
c++qtexceptionqt-creatorqmessagebox

Customize exceptions by showing error message C++ and Qt


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!


Solution

  • 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());
    }