ramyasri Amudala
PRO
last week
Ramyasricountry asked

#include <iostream> #include <exception> using namespace std; int main() { try { // allocate excessive memory to dynamically created array int* ptr = new int[1000000000000000]; // deallocate the memory delete[] ptr; } // catch exception if excessive memory is allocated // use object of exception class as catch argument catch (exception e) { cout << "Cannot allocate memory!!" << endl; cout << "Error: " << e.what() << endl; } return 0; } in the previous code we didnt write throw exception(); but in this below code i am unbale to get expected response u till i keep throw exception(); y

Abhay Jajodia
Expert
last week
Abhay Jajodia answered

Hello Ramyasri.

An exception is not raised automatically for every error.
A catch block runs only if something is thrown.

Case 1: When you don’t need throw

Some C++ operations already know how to handle failure.
Memory allocation with new is one of them.

If new fails:

  • C++ automatically throws an exception

  • Control jumps directly to catch

  • You don’t need to write throw yourself

So it feels like “magic”, but it’s actually built-in behavior.


Case 2: When you do need throw

In normal program logic (conditions, calculations, validations) and the current task in the lesson is calculation:

  • C++ does not assume anything is an error

  • Even if something is “wrong” by your logic, C++ keeps running

  • No exception exists unless you explicitly create one

So unless you write throw, there is:

  • No exception

  • Nothing for catch to catch

  • No error message

I hope I was able to explain it clearly. If you still have any confusion, please feel free to message me again and I’ll be happy to explain it in more detail.

Thank you for your question. keep up the great work in your learning journey! I look forward to hearing more questions from you.

C++
This question was asked as part of the Learn C++ Intermediate course.