Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

exception

We have a QT based C++ application. In which we are using third party DLL files 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 occurred...";
    }

    return a.exec();
}

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

like image 669
hetal agrawal Avatar asked Oct 24 '25 16:10

hetal agrawal


1 Answers

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.

like image 76
Blastfurnace Avatar answered Oct 26 '25 06:10

Blastfurnace



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!