This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
How to handle failure in constructor in C++?
Is there any pattern in C++ so i could terminate object creation in constructor if something fails? And so client that invoke constructor got information about failed obj creation?
Yes, you can: throw an exception. This is pretty much the only sensible way. By choosing the appropriate exception class (either standard or your own) and supplying a good error message etc you'll be able to tell the caller what's gone wrong.
The FAQ has more details.
You need to throw an exception. That is the best way to handle failing object creation.
Constructor Failures should be an Interesting read from Herb Sutter's GOTW.
Another way of doing this is that if a constructor encounters an error, set a status bit and let the user call IsOK() to see if construction actually worked.
But this is considered Obsolete.
Herb Says:
I have found the "if a constructor encounters an error, set a status bit and let the user call IsOK() to see if construction actually worked" method to be outdated, dangerous, tedious, and in no way better than throwing an exception.
Throwing an exception is the usual way to handle that, however, i discourage you from the pattern of throwing exceptions in constructors.
We cannot ensure that a constructor will not throw an exception but it seems to me an anti-pattern to rely on exceptions thrown by constructors.
There is a subtle difference :)
I usually prefer to deal with constructors that should not fail, and move the sensible logic that can fail in an Initialize method that can return a value or throw an exception.
It is more clean and avoid you bad headache when the code gets more complicated!
This is an example of why I blieve so: http://www.cs.technion.ac.il/~imaman/programs/throwingctor.html
Another interesting post is C++ : handle resources if constructors may throw exceptions (Reference to FAQ 17.4]
As aix explained, throwing from constructor is the only sensible option.
Alternatively, you can use Named Constructor Idiom (see here and here) and return null pointer if creation of new object ends up with failure.
Related
Background
Suppose we have an implementation of the abstract factory which is invoked as follows:
std::string ObjectName = "An Object Name";
std::string Args = "Argument passed directly to constructor by the factory";
std::unique_ptr<MyBaseClass> MyPtr(ObjectFactory::Instance().Construct(ObjectName,Args));
The factory uses a std::map to turn "An Object Name" into a constructor, which itself takes a std::string as an argument. The idea is that the user knows more about the constructed objects than I do, so I should get out of the way and let the user pass any information they want to the constructor.
Question
This works fine when Args is in exactly the form expected but I don't know the most idiomatic way of handling duff inputs. What should happen if a user supplies an invalid argument string?
I can think of the following:
have the object's constructor throw an exception
require the object provides a bool Validate(std::string x) method, which checks whether x is a valid argument string
Have the factory use the default constructor, and then call an initialisation method afterwards (begs the question: what if the init method fails?)
Set a bool member variable which, if true, means "this object is not in a sane state"
Some other option I've not thought of
Throw an exception. You're constructing an object (albeit in a different way than just new), failure is an exception that needs to be handled if it can happen.
"Solution 2" has nothing to do with handling this issue, it's more of a how to determine bad input. For such it can be an acceptable solution, but again it has nothing to do with the question at hand.
Solution 3 leaves the object in an indeterminate state in case of failure, which is unacceptable.
Solution 4 is another way to do it, and the only way if you don't have exception support in your language, but we do. Exceptions in this case are strictly better in my opinion because failing to construct an object is an action so destructive it should require alternative code or the program to die.
The first solution is the standard solution for constructor failure.
Solution #2 and #4 are pretty error prone (user might forget to check)
Solution #3 doesn't solve the problem
If you're making a library or just writing code that might be re-used in a "no exceptions allowed" environment, you could consider returning std::unique_ptr{nullptr}. Even if it is also error prone, that's the other standard way of handling construction failure.
Maybe the easiest way is to return a nullptr.
What ever you do, do not throw an exception from a constructor (as per Item #10 in More effective C++), as the destructor will not be called. It leads to newbie memory leaks and forces users to worry about exception handling.
I would just assert and return a Null Object, with dummy factory method implementations, or return nullptr.
I am C# programmer but now I want to get more into C++.
I know the basics of C++ but I don't know how to handle errors.
For example: I am writing a library. I create an constructor which requests an integer as an argument.
If that integer is bigger than 50, it is an error.
In C# I would throw an ArgumentOutOfRange exception, but what should I do in C++?
In C# I would throw an ArgumentOutOfRange exception but what should I do in c++?
First you should consider if that should not be a precondition of your function, leaving the responsibility of checking whether the value is in range to the caller.
If you decide for this option, then invoking the function with an out-of-range value would be undefined behavior, and inside the function you could just have a debug assertion to help you spot possible misuses - without the need of throwing any exception.
If you decide that the function should have a wide contract, on the other hand, and react in a well-defined way by throwing an exception when the argument is outside the permitted range, then you could throw an std::out_of_range exception.
For example: I am writing a libary [...]
If you are writing a library, meaning that you do not know the exact requirements of your clients in terms of performance and robustness, you may consider providing two such functions - one with a wide contract that throws exceptions, and one with a narrow contract that assumes the client provides meaningful input.
This way, the user of your library could decide based on their use cases whether or not it is OK to pay for the overhead of checking the correctness of the input each time your function is called.
This is, for instance, the strategy adopted by the C++ Standard Library for std::vector, which provides a non-throwing operator[] with a narrow contract for accessing elements of the collection based on the index (this function has undefined behavior if the index is out-of-bounds), and a member function at() that performs index checking and throws an exception if the index is out-of-bounds.
It depends on whether an integer larger than 50 could possibly be passed to the constructor as part of normal program flow, or whether that's an exceptional condition. But in general the only way to have object construction fail is by throwing an exception.
Your user code might look like this:
int n = parse_user_input()
if (n < 50)
{
Foo x(n);
x.do_cool_stuff();
}
else
{
// report user error
}
That is, you don't actually use exceptions for normal control flow. With that sort of code pattern, it would be perfectly fine for Foo::Foo(int) to throw an exception if the argument were out of range.
You can find useful standard exception classes in <stdexcept>.
The same thing as in C#: throw an exception. This is the only way to prevent an object from being constructed.
std::invalid_argument is a good standard choice regarding what to throw.
From the C++ FAQ: [17.8] How can I handle a constructor that fails?
Excerpt:
Throw an exception.
Constructors don't have a return type, so it's not possible to use
return codes. The best way to signal constructor failure is therefore
to throw an exception. If you don't have the option of using
exceptions, the "least bad" work-around is to put the object into a
"zombie" state by setting an internal status bit so the object acts
sort of like it's dead even though it is technically still alive.
So, throwing std::invalid_argument or std::out_of_range would be perfectly acceptable for your situation. You could also throw a custom exception if that would be beneficial in your situation. In the C++ FAQ see: [17.12] What should I throw?
I know that throwing from a destructor is in general a bad idea, but I was wondering if i could use std::uncaught_exception() to safely throw from a destructor.
Consider the following RAII type:
struct RAIIType {
...
~RAIIType() {
//do stuff..
if (SomethingBadHappened()) {
//Assume that if an exception is already active, we don't really need to detect this error
if (!std::uncaught_exception()) {
throw std::runtime_error("Data corrupted");
}
}
}
};
Is this UB in c++11? Is it a bad design?
You have an if, did you think about the "other" condition? It can throw an exception or... do what? There's two things that can be in the other branch.
Nothing (If nothing needs to happen when the error occurs, why throw an exception?)
It "handles" the exception (If it can be "handled", why throw an exception?)
Now that we've established that there's no purpose to throwing an exception conditionally like that, the rest of the question is sort of moot. But here's a tidbit: NEVER THROW EXCEPTIONS FROM DESTRUCTORS. If an object throws an exception, the calling code normally checks that object in some way to "handle" the exception. If that object no longer exists, there's usually no way to "handle" the exception, meaning the exception should not be thrown. Either it's ignored, or the program makes a dump file and aborts. So throwing exceptions from destructors is pointless anyway, because catching it is pointless. With this is mind, classes assume that destructors won't throw, and virtually every class leaks resources if a destructor throws. So NEVER THROW EXCEPTIONS FROM DESTRUCTORS.
Note that your code doesn't do what you think it does. In case SomethingBadHappened and there is no stack unwinding in place, you attempt to throw from a destructor and nonetheless std::terminate is called. This is the new behavior in C++11 (see this article). You will need to annotate your destructor with noexcept(false) specification.
Suppose you do this, it is not clear what you mean by "safely". Your destructor never triggers std::terminate directly. But calling std::terminate is not a UB: it is very well defined and useful (see this article).
For sure, you cannot put your class RAIIType into STL containers. The C++ Standard explicitly calls that UB (when a destructor throws in an STL container).
Also, the design look suspicious: the if-statement really means "sometimes report a failure and sometimes not". Are you fine with this?
See also this post for a similar discussion.
I know that throwing from a destructor is in general a bad idea, but I was wondering if i could use std::uncaught_exception() to safely throw from a destructor.
You may like to have a look at uncaught_exceptions proposal from Herb Sutter:
Motivation
std::uncaught_exception is known to be “nearly useful” in many situations, such as when implementing an Alexandrescu-style ScopeGuard. [1]
In particular, when called in a destructor, what C++ programmers often expect and what is basically true is: “uncaught_exception returns true iff this destructor is being called during stack unwinding.”
However, as documented at least since 1998 in Guru of the Week #47, it means code that is transitively called from a destructor that could itself be invoked during stack unwinding cannot correctly detect whether it itself is actually being called as part of unwinding. Once you’re in unwinding of any exception, to uncaught_exception everything looks like unwinding, even if there is more than
one active exception.
...
This paper proposes a new function int std::uncaught_exceptions() that returns the number of exceptions currently active, meaning thrown or rethrown but not yet handled.
A type that wants to know whether its destructor is being run to unwind this object can query uncaught_exceptions in its constructor and store the result, then query uncaught_exceptions again in its destructor; if the result is different, then this destructor is being invoked as part of stack unwinding
due to a new exception that was thrown later than the object’s construction.
It depends what you mean by "safely".
That will prevent one of the issues with throwing from a destructor - the program won't be terminated if the error happens during stack unwinding when handling another exception.
However, there are still issues, among them:
If you have an array of these, then they may not all be destroyed if one throws on destruction.
Some exception-safety idioms rely on non-throwing destruction.
Many people (such as myself) don't know all the rules governing what will or won't be correctly destroyed if a destructor throws, and won't be confident that they can use your class safely.
Should scoped objects (with complimentary logic implemented in constructor and destructor) only be used for resource cleanup (RAII)?
Or can I use it to implement certain aspects of the application's logic?
A while ago I asked about Function hooking in C++. It turns out that Bjarne addressed this problem and the solution he proposes is to create a proxy object that implements operator-> and allocates a scoped object there. The "before" and "after" are implemented in the scoped object's constructor and destructor respectively.
The problem is that destructors should not throw. So you have to wrap the destructor in a try { /* ... */ } catch(...) { /*empty*/ } block. This severely limits the ability to handle errors in the "after" code.
Should scoped objects only be used to cleanup resources or can I use it for more than that? Where do I draw the line?
If you pedantically consider the definition of RAII, anything you do using scoping rules and destructor invocation that doesn't involve resource deallocation simply isn't RAII.
But, who cares? Maybe what you're really trying to ask is,
I want X to happen every time I leave function Y. Is it
abusive to use the same scoping rules and destructor invocation that
RAII uses in C++ if X isn't resource deallocation?
I say, no. Scratch that, I say heck no. In fact, from a code clarity point of view, it might be better to use destructor calls to execute a block of code if you have multiple return points or possibly exceptions. I would document the fact that your object is doing something non-obvious on destruction, but this can be a simple comment at the point of instantiation.
Where do you draw the line? I think the KISS principle can guide you here. You could probably write your entire program in the body of a destructor, but that would be abusive. Your Spidey Sense will tell you that is a Bad Idea, anyway. Keep your code as simple as possible, but not simpler. If the most natural way to express certain functionality is in the body of a destructor, then express it in the body of a destructor.
You want a scenario where, guaranteed, the suffix is always done. That sounds exactly like the job of RAII to me. I however would not necessarily actually write it that way. I'd rather use a method chain of templated member functions.
I think with C++11 you can semi-safely allow the suffix() call to throw. The strict rule isn't "never throw from a destructor", although that's good advice, instead the rule is:
never throw an exception from a destructor while processing another
exception
In the destructor you can now use std::current_exception, which I think verifies the "while processing another exception" element of the destructor+exception rule. With this you could do:
~Call_proxy() {
if (std::current_exception()) {
try {
suffix();
}
catch(...) {
// Not good, but not fatal perhaps?
// Just don't rethrow and you're ok
}
}
else {
suffix();
}
}
I'm not sure if that's actually a good idea in practise though, you have a hard problem to deal with if it throws during the throwing of another exception still.
As for the "is it abuse" I don't think it's abusive anymore than metaprogramming or writing a?b:c instead of a full blown if statement if it's the right tool for the job! It's not subverting any language rules, simply exploiting them, within the letter of the law. The real issue is the predictability of the behaviour to readers unfamiliar with the code and the long term maintainability, but that's an issue for all designs.
Can anyone explain Exception Specifications as used in C++ ?
When are they used (I have rarely seen it used in code)
What are the pros and cons (benefits/disadvantages) of using exception specifications?
When are they used (I have rarely seen it used in code)
Hopefully never as they are deprecated in the next version of C++ due for standardization next year.
What are the pros and cons (benefits/disadvantages) of using exception specifications?
They provide a way for readers of your code to know exactly what exceptions a function is allowed to throw. The problem is, that if an unexpected exception (one not in the specification) is thrown, then the program will be terminated (by default).
They are generally regarded as a bad idea.
They say what a method will throw. The downside is that if that method throws anything else then your app terminates. So it's a guarantee but not in the same way that Java does it. And it adds the overhead of inspection.
The important thing to know is: exception specifications are deprecated in the next revision of C++, except for the no-throw specifier (throw()), which is basically officially saying "don't use them".
Putting throw() after a function means the function does not throw any exceptions. If it does anyway, the application will be terminated (probably - the unexpected handler is called), so the rest of your application can use that function knowing it will not throw an exception. This is can be handy for writing exception-safe code.
Example:
void MyFunction() throw() // does not throw any exceptions
{
/* ... */
{
They indicate to the programmer which exceptions will be thrown from that function. They have the advantage that you have the guarantee that no other exceptions can be thrown from that function. However, there is no compile-time checking of whether the function actually throws any exceptions other than what is indicated in the throw specifier. Instead, it's checked at runtime. And if it fails, then unexpected() is called, which by default calls abort() which in turn by default terminates your program. So, unless you really want your program to die if you screw up and an unexpected exception gets thrown, it's probably a bad idea to use them.
The one place where I would actually recommend using them is on destructors. It's really bad if a destructor throws. They should never throw. So, if you use throw() on a destructor to indicate that it can't throw an exception, then you know that your program will die rather than continue in the bad state that it would be in after an exception was thrown from a destructor.
Regardless, if you use any kind of throw specifier, you have to be sure that you really do want your program to die if it's violated. So, generally-speaking, it's best not to use them.
Basically, exception specifications allow the compiler to optimize the stack. The disadvantage is that it's a hell of a lot of extra spec. This means that you commonly see it in library work but not so much in working code.
I believe there's also some compile-time exception-safety thing going on, but since I've never used it, I can't be sure.