Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating My Own Exception In QT and Throwing an Exception in a Function

I am trying to make my own exception class in Qt. This is the first time I am doing it and I am confused as to how to throw my exemption inside of functions called in the main.

What I Have Currently:

myExcption.h

#ifndef MYEXCEPTION_H
#define MYEXCEPTION_H

#include <qtconcurrentexception.h>
#include <QDebug>

class MyException: public QtConcurrent::Exception
{
public:
    void raise() const {qDebug() << "\nException: "; throw *this;}
};

#endif // MYEXCEPTION_H

Now currently how I throw exemptions is this:

myFuction.h

void Commands(QString Command_in, MyException &wrongInput);

myFunction.cpp

void Command(QString Command_in, MyException &wrongInput)
{
    if(Command_in != "some string")
    {
        wrongInput.raise();
    }
}

main.cpp

String s = "some String";
MyException wrongString;
try
{
   Command(s, wrongString);
}
catch(MyException &wrongString)
{
   qDebut << "String invalid";
}

Now this works, but I feel as if I should not have to pass in a reference of my exception to every function. What are my options? Here is what I feel I should be able to do, but I am not sure how to do it.

myFunction.cpp

void Command(QString Command_in)
{
    if(Command_in != "some string")
    {
        throw myException;
    }
}

main.cpp

QString s = "some String";
try
{
   Command(s);
}
catch(MyException &wrongString)
{
   qDebut << "String invalid";
}

Is this possible?

like image 946
user1334858 Avatar asked Oct 21 '22 13:10

user1334858


1 Answers

You're almost there. In a throw statement, you usually throw a temporary object of the exception class. E.g.

void Command(QString Command_in)
{
    if(Command_in != "some string")
    {
        throw MyException{};
    }
}

Technically, there's nothing wrong with naming the object, but it's one line longer and not more readable:

void Command(QString Command_in)
{
    if(Command_in != "some string")
    {
        MyException someRandomName;
        throw someRandomName;
    }
}

Of course, this means you don't need a raise() method either. But if you would want one, it really should be static :

class MyException: public QtConcurrent::Exception
{
public:
    static void raise() const {qDebug() << "\nException: "; throw MyException{};}
};
like image 63
MSalters Avatar answered Oct 30 '22 16:10

MSalters