-5
#include <iostream>

int main()
{
int num = 1;

try
{
    if (num != 0)
    {
        throw "num is not 0!";
    }
}
catch (char *x)
{
    cout << x << endl;
}
}

I want this code to print "num is not 0!" to cout but when i run it i get libc++abi.dylib: terminating with uncaught exception of type char const* Abort trap: 6 as output from the terminal. Am I misunderstanding how exceptions work or is there some other problem?

Blink
  • 163
  • 1
  • 6
  • 4
    The message states `type: char const* ` – JVApen Feb 21 '18 at 18:18
  • See https://stackoverflow.com/questions/35528780/c-a-few-questions-about-throwing-exceptions?rq=1 – jpw Feb 21 '18 at 18:19
  • Maybe you are confused as to what the `throw "num is not 0!";` statement does. It's not the one that outputs the string literal on the standard output. The catch block does that. Also this compiles with Visual Studio while it does not with GCC. String literal is of type `const char*` not `char*`. – Ron Feb 21 '18 at 18:27
  • 1
    Just saying; as a general rule of thumb, exceptions should always be caught by const reference `catch (const& whatever)`. – Jesper Juhl Feb 21 '18 at 18:30
  • Prefer instead to throw `std::runtime_error{"num is not 0!"}` and log it with `std::exception::what()`. – Chad Feb 21 '18 at 19:24

1 Answers1

3

This is because you throw a string literal and it cannot be bound to char*. Rather it can be bound to char const*.

Pedantically, the type of "num is not 0!" is char const[14], however, in throw expression the array decays to a pointer to its first element.

Maxim Egorushkin
  • 131,725
  • 17
  • 180
  • 271