I'm programming some exercises about exceptions in C++ with NetBeans 8.1 Patch 1 on Windows 10 using MinGW 64 bits, but the expected result is not the same when I execute the code in IDE.
Here's the code:
#include <cstdlib>
#include <iostream>
using namespace std;
void f() {
throw 'A';
}
int main() {
try {
try {
f();
} catch (int) {
cout << "In catch (int) 1" << endl;
throw;
} catch (...) {
cout << "In catch (...) 1" << endl;
throw 65;
}
} catch (int&) {
cout << "In catch (int&)" << endl;
} catch (int) {
cout << "In catch (int) 2" << endl;
} catch (const int) {
cout << "In catch (const int)" << endl;
} catch (...) {
cout << "In catch (...) 2" << endl;
}
cout << "End of program" << endl;
return EXIT_SUCCESS;
}
The terminal displays this :
In catch (int) 1
In catch (int&)
End of program
Normally, the terminal should display in the first line "In catch(...) 1", but I don't understand why the IDE doesn't display the good result.
I tried this code with g++ on PowerShell, same result, but with g++ on Linux Ubuntu, he displays the right result.
I don't have any suggestions.
Thank you for your help. Kind regards.
Integral promotions are considered when a suitable catch is searched for. 'A' is a character literal and is promoted to an int.
Thus:
throw 'A'; is performed;catch (int) after integral promotion;throw; rethrows the same object (no copy is made);catch (int&) catches it (note: catch (int) could catch it but it is not the nearest catch);For your information, [except.throw]/2 explains what nearest means:
When an exception is thrown, control is transferred to the nearest handler with a matching type (
[except.handle]); “nearest” means the handler for which the compound-statement or ctor-initializer following the try keyword was most recently entered by the thread of control and not yet exited.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With