What do you call a function that returns a link or throws an exception without gymnastics?

Suppose you are presented with the following code:

blah & Foo::foo() { 
   if (_x) {  return _blah;}
   throw exception("blah error");
}

As far as I can tell, the only way to name it in a try / catch block like this

try {
blah &b=_foo.foo();
catch(...) {}

Now b goes out of scope, which makes error handling more difficult. You can assign it to a pointer, and then reassign the pointer to the link below, but it seems rather complicated.

I don’t remember the explicit suggestion to avoid creating functions that return links or throw exceptions, but is there a standard way around this problem when working with these types of interfaces?

+3
source share
4 answers

, , , . , , foo() try, , , . , , , :

try { 
    blah &b = _foo.foo();
    b.dehydrate();
    _foo.reconceptualize(b);
    idealize(b, _foo, "grumble");
} catch (const exception &x) {
    // log/handle error
}

, b foo(), , b , try foo(). , try, b, .

try {
    blah &b = _foo.foo();
    // <- [1] this is the only point that we *know* foo() returned something valid
} catch (...) {
    // <- [2] here we *know* it didn't
}

// <- [3] here we don't know either way

, , foo() b, 1, 2 3 , (: 1)?

, try, , . NULL, , , , :

blah *b;

try {
    b = _foo.fooptr();
    // <- here we know an error did not occur
} catch (...) {
    // <- here we know an error occurred
    b = NULL; // <- so why do this...
}

// ... when we already had a perfectly good opportunity to handle above;
// we've kind of missed the boat at this point.

, , . , - API - :

void * getData () {
    void *data = NULL;
    try {
        data = getFromThingThatMayThrow();
    } catch (...) {
        // we really don't care why it failed, and it more convenient to
        // swallow it and return NULL instead.
    }
    return data;
}

- , , , , , . .

0

, . , , . try/catch , .

, , .

+2

, , , , , try/catch.

, , , ( ), , , . .

, , . , , , , , , .

+1

Something like C ++ 1y might help here optional. I also saw an offer for expected<T,Otherwise>. You associate a pseudo-volume call with link or error information. You handle the error whenever you want, and otherwise access the data if you have verified that there are no errors.

This leads to traditional error handling in the string, rather than error handling based on the exceptions that some prefer.

0
source