Simo Pelle
Simo Pelle

Reputation: 169

Catch multiple exceptions

How can I catch more than one exceptions at once?

I mean, I have to do A if I get std::out_of_range or std::invalid_argument or B if I get std::runtime_error or std::bad_alloc

It is an example... There are some cases in which I have more than 5 exceptions that bring me to the same point.

I just hope I don't have to copy-paste the same code multiple times!

Upvotes: 4

Views: 2269

Answers (1)

Jesper Juhl
Jesper Juhl

Reputation: 31468

You don't copy'n'paste, you put code in functions and call the function in multiple cases.

Here's how:

try {
    /* Stuff */
} catch (const std::out_of_range&) {
    do_A();
} catch (const std::invalid_argument&) {
    do_A();
} catch (const std::runtime_error&) {
    do_B();
} catch (const std::bad_alloc&) {
    do_B();
}

If you need the same exception handling in multiple locations you can put it into a function like so:

void handle_exception() {
    try {
        throw; // re-throw the original exception our caller caught, so we can catch and handle specific ones.
    } catch (const std::out_of_range&) {
        do_A();
    } catch (const std::invalid_argument&) {
        do_A();
    } catch (const std::runtime_error&) {
        do_B();
    } catch (const std::bad_alloc&) {
        do_B();
    }
}

And then, at multiple places, you can do

try {
    /* Stuff */
} catch (...) {
    handle_exception();
}

Upvotes: 5

Related Questions