throwing exceptions on success

I'm wondering if there is a way to throw and exception inside the constructor for an object while still resulting in the creating of that object.

I have a tote object, and when you create that object you add a part # to it. If there are already other parts in the tote however, I want to force the caller to do something about those parts right after. However, I still want to create the object right from the start.

so basically i'd like to be able to do this:

1
2
3
4
5
try{
  tote = Tote(tote_name, part_num);
}catch(ToteFull&){
  tote.clear_old_parts();
}


then continue on with a tote object containing only the part I assigned to it.

I could probably not throw the exception, then have a method on tote called has_old_parts() which you could check on creation, then call the clear based on that, but a caller wouldn't be forced to do that they'd have to remember to.
It's almost like i'd like to throw a warning rather than an exception. Any ideas?
Last edited on
Exceptions, because they do incur some runtime penalty, are generally reserved for error cases, and
should not be used in the success case.
ischuldt wrote:
I'm wondering if there is a way to throw and exception inside the constructor for an object while still resulting in the creating of that object.

No.

In addition, your use case has a serious problem. Since the Tote you are constructing does not exist (otherwise what you are doing is not "construction"), there can be no other parts in the tote unless you put them there in the constructor yourself. QED.

Secondly, in your code example, the "tote" object in line 4 has not been defined in that scope. The tote you create on line two only exists until the closing brace on line 3, at which point it goes out of scope.
Topic archived. No new replies allowed.