#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?
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.