bwDraco
bwDraco

Reputation: 2542

Does an exception in one statement in a try block cause control flow to bypass any remaining statements in the try block?

I have some C++ code that looks like this:

void Student::addCourse(Course cVal, string gr) throw(...) {
    try {
        GradedCourse c(cVal, gr);  // If an exception is thrown here...
        coursesTaken.insert(c);    // will this statement be executed?
    } catch(...) {
        throw;
    }
}

The GradedCourse constructor may throw an exception if gr, which contains a grade for a course, is found to be invalid by the constructor. If such an exception occurs, will any further statements inside the try block be executed? Can I be sure that such an exception will result in no attempt to insert the GradedCourse into coursesTaken (which is an STL set)? I've searched both Stack Overflow and Google without much success.

Upvotes: 2

Views: 282

Answers (2)

Logan Nichols
Logan Nichols

Reputation: 397

Now I understand what you are trying to ask, but your title and question itself are both asking conflicting things. :)

If an exception is thrown inside of a try block, execution immediately jumps to the catch block that handles that exception, bypassing all other statements.

Here is the documentation on exceptions. It does not directly address your issue, but it does cover other important things such as exception nesting, or chaining exception handlers.

Upvotes: 0

alestanis
alestanis

Reputation: 21863

No.

If GradedCourse c(cVal, gr); throws an exception, nothing else inside the try block will be executed.

Upvotes: 2

Related Questions