131

while looking at some code I stumbled onto:

throw /*-->*/new std::exception ("//...

and I always thought that you don't need/you shouldn't use new here.
What is the correct way, are both OK, if so is there any difference?

BTW from what I can see while "grepping" with PowerShell boost libs never use throw new.

P.S. also I found some CLI code that uses throw gcnew. Is that OK?

CharlesB
  • 86,532
  • 28
  • 194
  • 218
NoSenseEtAl
  • 28,205
  • 28
  • 128
  • 277
  • 1
    I think `throw gcnew` would be useful eg. if you want managed code to catch your exception. Can somebody correct me on that? – jpalecek Jun 08 '12 at 12:05
  • 1
    .Net deals with exceptions by pointer, so throw gcnew is the right thing to do there. – Sebastian Redl Jun 08 '12 at 12:26
  • 1
    @SebastianRedl .Net "pointer" may be ambiguous? Though gcnew certainly isn't. `System::Exception` is generally a reference to a managed object on the garbage collected heap. I've always thrown with `gcnew` and caught with `System::Exception ^`. Of course I use `finally` all the time in C++/CLI as well, though don't often mix with C++ exceptions in the same `try` block, I'm not sure why. –  Apr 01 '13 at 15:29

5 Answers5

104

The conventional way to throw and catch exceptions is to throw an exception object and to catch it by reference (usually const reference). The C++ language requires the compiler to generate the appropriate code to construct the exception object and to properly clean it up at the appropriate time.

Throwing a pointer to a dynamically allocated object is never a good idea. Exceptions are supposed to enable you to write more robust code in the face of error conditions. If you throw an exception object in the conventional manner you can be sure that whether it is caught by a catch clause naming the correct type, by a catch (...), whether it is then re-thrown or not it will be destroyed correctly at the appropriate time. (The only exception being if it is never caught at all but this is a non-recoverable situation whichever way you look at it.)

If you throw a pointer to a dynamically allocated object you have to be sure that whatever the call stack looks like at the point you want to throw your exception there is a catch block that names the correct pointer type and has the appropriate delete call. Your exception must never be caught by catch (...) unless that block re-throws the exception which is then caught by another catch block that does deal correctly with the exception.

Effectively, this means you've taken the exception handling feature that should make it easier to write robust code and made it very hard to write code that is correct in all situations. This is leaving aside the issue that it will be almost impossible to act as library code for client code that won't be expecting this feature.

Jarod42
  • 203,559
  • 14
  • 181
  • 302
CB Bailey
  • 755,051
  • 104
  • 632
  • 656
  • 1
    "throw an exception object" stack or heap my friend? Stack or heap? (Maybe I was looking at a bad global example somewhere) oh and if stack, then what's the appropriate scope? –  Apr 01 '13 at 15:20
  • @ebyrob: I'm not really sure what you're asking about but it sounds like you want to know about the storage and/or lifetime of the exception object which might be answered [here](http://stackoverflow.com/questions/1654150/scope-of-exception-object-in-c). If not you might be better off asking a separate question. – CB Bailey Apr 01 '13 at 17:09
36

No need to use new when throwing exception.

Just write:

throw yourexception(yourmessage);

and catch as :

catch(yourexception const & e)
{
      //your code (probably logging related code)
}

Note that yourexception should derive from std::exception directly or indirectly.

Nawaz
  • 353,942
  • 115
  • 666
  • 851
  • 7
    Why? why not use `new`? why derive `yourexception` from `std::exception`? – Walter Jun 08 '12 at 12:53
  • When I'm lazy (which is waaay to often) why doesn't `throw std::exception;` work? g++ won't seem to compile it... –  Apr 01 '13 at 15:33
  • 7
    @ebyrob: `std::exception` is a type, and you cannot throw a *type*, you've to thrown an *object*. So the syntax should be this : `throw std::exception();` That will compile. Now how good that is, is a different question altogether. – Nawaz Apr 01 '13 at 15:46
23

Throwing new std::exception is correct if the call site is expecting to catch a std::exception*. But nobody will be expecting to catch a pointer to an exception. Even if you document that's what your function does and people read the documentation, they're still liable to forget and try to catch a reference to a std::exception object instead.

  • 29
    Throwing `new std::exception` is only correct if the call site is expecting to catch a pointer AND is expecting to take over management of the allocate exception AND there are never going to be any cases where you're function will be called by something that doesn't explicitly catch the correct pointer (`catch(...)` or no handling at all) otherwise there will be an object leak. In short, this can be approximated as "never". – CB Bailey Jun 08 '12 at 12:02
  • It's curious how this answer was accepted, when really it's @CharlesBailey's *comment* that is the correct answer. – John Dibling Jun 08 '12 at 14:54
  • @John: That crossed my mind too. But I think the one-two punch has good effect with me giving the dry summary and Charles amusingly expanding on the various the ways people are liable to forget to deal with it properly. Too bad you don't get reputation from up-voted comments, though. –  Jun 08 '12 at 15:21
  • Charles didnt provide his answer, and this A (unlike the other one )has explanations both in the A and comment. – NoSenseEtAl Jun 08 '12 at 15:28
9

The C++ FAQ has a nice discussion on this:

  1. https://isocpp.org/wiki/faq/exceptions#what-to-catch
  2. https://isocpp.org/wiki/faq/exceptions#catch-by-ptr-in-mfc

Basically "unless there's a good reason not to, catch by reference. Avoid catching by value, since that causes a copy to be made and the copy can have different behavior from what was thrown. Only under very special circumstances should you catch by pointer."

user1202136
  • 11,171
  • 4
  • 41
  • 62
  • 3
    As usual the FAQ is badly worded. You can catch by value or reference. A pointer just happens to be a value (that you catch by value or reference). Remember the type `A` is distinct from the type `A*` so if I do `throw A()` I can NOT catch with `catch(A* e)` as it is completely different type. – Martin York Jun 08 '12 at 15:37
  • These links are now broken. – stephenspann Oct 10 '15 at 16:41
  • 1
    I fixed the links @spanndemic – user1202136 Oct 11 '15 at 17:21
2

Operator new cannot guarantee that it will never raise an exception. For this reason using it for throwing a "valid" (intended) exception would produce a code that cannot be guaranteed not to crash. Since there may be only one exception at a time, and your program tries to throw two before any of them can be caught, the best thing an implementation can do is to immediately abort your program, e.g. by calling std::terminate.

zkoza
  • 2,644
  • 3
  • 16
  • 24