简体   繁体   中英

C++ try catch does not work for array out of bound

We have a QT based c++ application. In which we are using third party dlls too. But, C++ try and catch does not work at all.

For Example:

#include <QCoreApplication>
#include <QDebug>
#include <QException>

int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);

    int arr[10];
    try
    {
        arr[11] = 30;
    }
    catch (const std::out_of_range& e)
    {
        qDebug() << "Exception out of range occurred ..." << e.what();
    }
    catch (...)
    {
        qDebug() << "Unknown Exception occured...";
    }

    return a.exec();
}

Above is the minimal example. In above it crashes the program. Is there a way to handle this?

Reading or writing out of array bounds is undefined behavior. There's no guarantee that it will crash, throw an exception, or do anything at all. It's just malformed code.

If you want an array-like container with bounds checking there are std::array , std::vector , and perhaps std::deque in the standard library. They all have an at() member function that does bounds checking and will throw a std::out_of_range exception.

To answer your question:

"C++ try catch does not work for third party library"

No! C++ try catch does work with third party ( Qt ) library, as shown in the example below.

But the code that you are showing is not an mcve . Therefore it is difficult to say, what exactly is causing the problem that you say you are having.

#include <QCoreApplication>
#include <QDebug>
#include <QException>

class testException : public QException
{
public:
    testException(QString const& message) :
        message(message)
    {}

    virtual ~testException()
    {}

    void raise() const { throw *this; }
    testException *clone() const { return new testException(*this); }

    QString getMessage() const {
        return message;
    }
private:
    QString message;
};

int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);

    try
    {
        // throw std::out_of_range("blah");
        throw testException("blah");
    }
    catch (const std::out_of_range& e)
    {
        qDebug() << "Exception out of range occurred ...";
    }
    catch (...)
    {
        qDebug() << "Unknown Exception occured...";
    }

    return a.exec();
}

std::out_of_range

It may be thrown by the member functions of std::bitset and std::basic_string , by std::stoi and std::stod families of functions, and by the bounds-checked member access functions (eg std::vector::at and std::map::at )

Your try block has neither of these things. Out of bounds access to plain C style arrays is undefined behaviour . This is often manifested as crashes, as you have experienced.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM