0

What is the problem when we throw a pointer in C++. For example in below code, what happened for exception object?

class Box {
....
};

int main()
{
try
{
  throw new Box();
}

catch(Box* b)
{
...
}
}
Mahdad
  • 3
  • 1
  • 1
    What are you going to do if `new` fails? – user4581301 Jul 08 '20 at 18:30
  • Maybe throw null pointer to exception object. – Mahdad Jul 08 '20 at 18:34
  • If new fails, there is nothing to do but exit anyway. Catching new failure is useless – Michael Chourdakis Jul 08 '20 at 18:37
  • @MichaelChourdakis what about pointer to objects? – Mahdad Jul 08 '20 at 18:39
  • If you throw a different exception while throwing an exception, you've lost the information you were originally trying to convey. You could throw a pointer to an already existing object, but that object better have a lifetime that exceeds the distance the exception has to travel otherwise the receiver catches an invalid pointer and you're worse off than you were when you started. – user4581301 Jul 08 '20 at 18:43
  • Generally you don't need much try/catch anyway. – Michael Chourdakis Jul 08 '20 at 18:57
  • @MichaelChourdakis The reason `new` throws on failure is specifically so you *can* do something instead of just exiting. Maybe for some applications there isn't anything useful to do with that exception, but it is incorrect to make a blanket statement that it is never useful. And this is only considering that `new` might fail from memory allocation failure. `new` can also fail if a constructor throws. It would be odd for that to happen for an exception type but in other contexts it may be perfectly fine. This applies by exception, `std::make_shared`, etc. – François Andrieux Jul 08 '20 at 19:12
  • When we throw a pointer to a catch block, if pointer, points to a local object in try block, it has destroyed, when exception object create. does exception object point to null? – Mahdad Jul 09 '20 at 04:29

0 Answers0