DanielGr
DanielGr

Reputation: 311

Can I have a static global instance of an exception?

I have read in a few places that raising exceptions can be expensive. I have an exception that I expect to occur with some frequency and I will catch it each time. This may be a naive question (like many, I'm late to the exception game):

can I create a static global instance of my exception and throw it when it does arise (only from one method), catching it each time?

Will this even save me any time? Or since I expect to throw with some frequency, will only throw this exception from this one method (at the moment), and will always catch this exception, is this a sign that I should be using some other paradigm for handling this situation?

Thanks for any helpful answers!

Upvotes: 2

Views: 267

Answers (2)

Baum mit Augen
Baum mit Augen

Reputation: 50053

First to answer your real question:

can I create a static global instance of my exception and throw it when it does arise (only from one method), catching it each time?

No. The exception object thrown is always newly constructed, it is a unique object each time. Also, the construction of the exception object is not what's expensive, the exceptional control flow is. But

Or since I expect to throw with some frequency, will only throw this exception from this one method (at the moment), and will always catch this exception, is this a sign that I should be using some other paradigm for handling this situation?

Yes, definitely. Exceptions are for exceptional errors, not for stuff you would expect to happen. Returning some status code or state like the standard streams does sound a lot more appropriate.

Upvotes: 3

Cheers and hth. - Alf
Cheers and hth. - Alf

Reputation: 145224

Exception are thrown by value, not by reference, so simply having an instance of your exception class at hand, won't help.

However, there is a possibility that rethrow_exception (it requires an exception_ptr as argument) might be more efficient, with some given compiler and options on some given system. You will have to measure to determine this.

Worth noting that with most (all?) C++ implementations the exception machinery is optimized for code that only very rarely throws exceptions. Thus, having the execution pass through try blocks etc. is mostly free, no-cost. But the action of throwing can be costly. So yes, if you can, do consider some other “paradigm” for whatever the task is. E.g., it might be that you can return a 1boost::optional<T>, which is like a box that either contains an object or nothing.


1 If you want to avoid a dependency on Boost then an Optional class for POD type is trivial to implement, and for non-POD one can leverage a std::vector as object carrier, at the cost of a possible dynamic allocation.

Upvotes: 4

Related Questions