My compiler gives me an error for the following code:
#include <iostream>
#include <stdexcept>
using namespace std;
void test()
{
throw runtime_error("Error");
}
int main()
{
try
{
test();
}
for (int i = 0; i < 10; i++)
{
}
catch (exception& e)
{
cout << e.what();
}
}
It says "error: expected 'catch' before '(' token", and it's referring to the '(' in the for loop initialization.
Do I have to write the catch block immediately after the try block? I thought that if an error is thrown in the try block, the program will bubble out until it finds an appropriate catch block. Why doesn't that apply here?