throw new std::exception vs throw std::exception
Asked Answered
P

5

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?

Perlite answered 8/6, 2012 at 11:51 Comment(3)
I think throw gcnew would be useful eg. if you want managed code to catch your exception. Can somebody correct me on that?Tsaritsyn
.Net deals with exceptions by pointer, so throw gcnew is the right thing to do there.Vannessavanni
@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.Carriecarrier
B
105

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.

Bort answered 9/6, 2012 at 20:44 Comment(2)
"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?Carriecarrier
@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. If not you might be better off asking a separate question.Bort
E
37

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.

Ephemerality answered 8/6, 2012 at 11:53 Comment(3)
Why? why not use new? why derive yourexception from std::exception?Jugendstil
When I'm lazy (which is waaay to often) why doesn't throw std::exception; work? g++ won't seem to compile it...Carriecarrier
@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.Ephemerality
U
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.

Untouchable answered 8/6, 2012 at 11:58 Comment(4)
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".Bort
It's curious how this answer was accepted, when really it's @CharlesBailey's comment that is the correct answer.Larger
@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.Untouchable
Charles didnt provide his answer, and this A (unlike the other one )has explanations both in the A and comment.Perlite
C
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."

Cassiecassil answered 8/6, 2012 at 12:4 Comment(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.Gildus
These links are now broken.Talyah
I fixed the links @spanndemicCassiecassil
G
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.

Gramarye answered 29/11, 2019 at 0:14 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.