How Do I Continue to the Next Iteration of a for Loop After an Exception is Thrown in C++?
Last Updated :
22 Feb, 2024
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++
#include <iostream>
#include <stdexcept>
using namespace std;
int main()
{
for ( int i = 1; i <= 5; ++i) {
try {
if (i == 3) {
throw runtime_error( "Exception occurred!" );
}
cout << "Iteration " << i
<< endl;
}
catch ( const runtime_error& e) {
cerr << "Caught exception: " << e.what()
<< endl;
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.
Share your thoughts in the comments
Please Login to comment...