Matthew Yang
Matthew Yang

Reputation: 625

Why does throw itself cause an exception?

I have a piece of C++ program that can not be simpler

#include <string>
#include <iostream>
using namespace std;

void throwE(){
  throw "ERROR";
}

int main(int argc, char* argv[]){
  try{
    throwE();

  } catch(const std::string& msg){
    cerr << msg << endl;
  }
  return 0;
}

But it raises an exception when run:

libc++abi.dylib: terminate called throwing an exception
Abort trap: 6

Can anyone tell me why this happens, why is the exception not caught?

Upvotes: 0

Views: 139

Answers (1)

juanchopanza
juanchopanza

Reputation: 227390

You aren't throwing an std::string, but a nul terminated string (the type of "ERROR" is really const char[6], and the throw expression decays that to const char*.). So you don't catch the exception. If you change throwE to throw an std::string, it works as expected:

void throwE(){
  throw std::string("ERROR");
}

Alternatively, catch a const char*, which matches the type of the exception thrown after the const char[6] decays to const char*:

} catch(const char* msg){
  cerr << msg << endl;
}

Output:

ERROR

Upvotes: 8

Related Questions