What I'm trying to do is write code that breaks out of a for loop if an exception is thrown. Can this be achieved by simply using return in the catch block? or do I have to use break somehow?
for example, 1. will this function return 0 or 1? 2. will the first return statement break the for loop or 3. will it keep on looping?
Thank you in advance!!
int main() {
for (int i = 0; i < 2; i ) {
try {
if (i = 0) {
throw fake_error;
}
}
catch(fake_error) {
return i;
}
}
return i;
}
CodePudding user response:
Any block can try catch, though while allowed I recommend to use a bigger scope. (exceptions are the biggest exception to the "don't pay for what you don't use" rule in c ).
To avoid having to put your exception into the inner loop you can create your own exception and put the information you want to have available in the catch block inside the exception. So this example shows you how to do that, also catch exceptions by const& this will avoid unecessary copying and/or modification of the exception content.
#include <stdexcept>
//-------------------------------------------------------------------------
// declare/define an exception that can hold an int.
class my_exception :
std::exception
{
public:
// always declare constructors with one parameter explicit
// or they can be used in implicit type-conversions
explicit my_exception(const int value) :
m_value{ value }
{
}
// accessor to data
const int& value() const noexcept
{
return m_value;
}
private:
int m_value;
};
//-------------------------------------------------------------------------
int main()
{
int retval{ 0 };
// with our own exception we can
// move the try-catch block out of the loop.
try
{
for (int i = 0; i < 2; i)
{
if (i == 1) throw my_exception(i);
}
}
catch(const my_exception& e)
{
retval = e.value();
}
return retval;
}
CodePudding user response:
Yes.
C allows try/catch inside any block of statements, including a for()
loop block.
However, you may want to consider doing it otherwise if possible just because it is slow (if the for() is only expected to go over a small number of iterations, then not big deal).