Open In App

How Do I Continue to the Next Iteration of a for Loop After an Exception is Thrown in C++?

Last Updated : 22 Feb, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

In C++, when an exception is thrown, the normal flow of the program is disrupted and we need to take care of it. In this article, we will learn how can we continue to the next iteration of a for loop after an exception is thrown in C++.

Continue Loop After an Exception is Thrown in C++

To continue to the next iteration of a for loop after an exception is thrown, we can enclose the code that might throw an exception within a try block and handle the exception in a catch block inside the loop itself. Then proceed to the next iteration using the continue statement after handling the exception.

C++ Program to Continue to the Next Iteration of a Loop After Throwing an Exception

The below example demonstrates how we can continue to the next iteration of a loop after an exception is thrown in C++.

C++




// C++ program to continue to the next iteration of a for
// loop after an exception is thrown in C++
  
#include <iostream>
#include <stdexcept>
  
using namespace std;
  
int main()
{
  
    // for loop
    for (int i = 1; i <= 5; ++i) {
        try {
            // Your code that might throw an exception
            if (i == 3) {
                // Throw a runtime_error exception
                throw runtime_error("Exception occurred!");
            }
  
            // Continue with the rest of the loop body if no
            // exception is thrown
            cout << "Iteration " << i
                 << endl; // Print the iteration number
        }
  
        catch (const runtime_error& e) {
            // Handle the exception
            cerr << "Caught exception: " << e.what()
                 << endl;
            // Continue to the next iteration of the loop
            continue;
        }
    }
  
    return 0;
}


Output

Iteration 1
Iteration 2
Caught exception: Exception occurred!
Iteration 4
Iteration 5

Explanation: In the above example the code that might raise an exception is contained in the try block and the catch block handles exceptions and to continue to the next iteration continue statement is used.



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads