0

This may be me overlooking something basic, but the code below has no output or exceptions shown in my terminal. (using g++ in Cygwin) First Code:

#include <iostream>
#include <vector>
#include <string>


using namespace std;

int main(){
cout << "main";
vector<string> v;
v.at(0)= "HI";
return 0;
}

Second Code:

#include <iostream>
#include <vector>
#include <string>


using namespace std;

int main(){
cout << "main" <<endl;
vector<string> v;
try{
v.at(0)= "HI";
}catch(const std::exception &exc){
    cout << exc.what()<<endl;
}
return 0;
}

which has the expected output of :

main

vector::_M_range_check: __n (which is 0) >= this->size() (which is 0)

is there a reason why the first code doesn't give an exception or any output?

  • The expected exception gets reported on Linux. Something to do with cygwin's environment, most likely. – Sam Varshavchik Feb 02 '20 at 03:28
  • @walnut yes, thanks for linking ill remove for duplicate soon. Does g++ recognize that there is an exception and hence doesn't print main even though the print statement is before the run-time-exception? – Rehmaan Momin Feb 02 '20 at 03:35
  • Neither `g++` not `clang++` does such optimizations (unless they have bugs). It'd have observable side effects. – Ted Lyngmo Feb 02 '20 at 03:50
  • @TedLyngmo If an exception escapes `main`, then `std::terminate` will be called which in turn calls `std::abort` by default. It is implementation-defined whether stack unwinding is done in that case and static destructors are not called. So `std::cout` wont be flushed, which OP is observing. But yes, the compiler is not allowed to reorder instructions changing the side effects only because there will always be an exception thrown that escapes `main`. – walnut Feb 02 '20 at 03:58
  • @OP You need to flush the stream, e.g. by adding `<< endl;` to the `cout` statement. Otherwise the exception is thrown when your output is still in the stream buffer, not flushed yet, and then the uncaught exception will abort the program before the stream can be flushed. – walnut Feb 02 '20 at 03:59
  • @walnut Since C++17: `vector() noexcept`. Before C++17, yes, that's possible. - perhaps I'm reading like crap again. I'm just looking at the catching code. :-) Oh, yes ... I am... – Ted Lyngmo Feb 02 '20 at 04:04
  • @TedLyngmo I am not sure what you want to say. The exception here is thrown by `.at(0)`, not the constructor. – walnut Feb 02 '20 at 04:07
  • @walnut Yeah, but one of my mistakes was looking at the second code snippet only and the constructor was the only one outside the `try` ... `catch`. My bad. – Ted Lyngmo Feb 02 '20 at 04:08
  • "_is there a reason why the first code doesn't give an exception or any output?_" - It calls `[[noreturn]] void terminate() noexcept`. since you don't have any exception handler for it. The output may as walnut says be truncated. – Ted Lyngmo Feb 02 '20 at 04:10

0 Answers0