SNR_BT
SNR_BT

Reputation: 183

Why exception caught without throwing in C++?

I am running this program. As per my understanding, there should be a bad allocation exception raised within the try block and should cause a runtime failure. However, the program executes without any problem. I have the following questions:

  1. Why is there no run-time error?

  2. How does the control reach catch block even when no exceptions were thrown?

    #include <iostream>
    using namespace std;
    
    int main() {
        int b =4, *c = NULL, i=-1;
        try{
            c = new int [i]; 
            b--;
        }catch (exception& e){
            cout << "coming here" << endl;
            c = new int[1];
            b++;
        }
        cout << b << endl;
        return 0;
    }
    

Upvotes: 0

Views: 72

Answers (2)

Bathsheba
Bathsheba

Reputation: 234875

-1 will be converted to the std::size_t value std::numeric_limits<std::size_t>::max() due to the implicit conversion to an unsigned type. It is indeed unlikely that you have that much memory available.

However a std::bad_alloc might not be thrown if your operating system doesn't actually allocate the memory until you consume it (common on linux platforms).

See lazy allocation for c++ object arrays

Upvotes: 3

trenki
trenki

Reputation: 7363

Your c = new int [i] within the try block throws the exception because it cannot allocate the memory (i=-1), so the catch block will be executed.

Upvotes: 1

Related Questions