I have the following code.
#include "math.h" // for sqrt() function
#include <iostream>
using namespace std;
int main()
{
cout << "Enter a number: ";
double dX;
cin >> dX;
try // Look for exceptions that occur within try block and route to attached catch block(s)
{
// If the user entered a negative number, this is an error condition
if (dX < 0.0)
throw "Can not take sqrt of negative number"; // throw exception of type char*
// Otherwise, print the answer
cout << "The sqrt of " << dX << " is " << sqrt(dX) << endl;
}
catch (char* strException) // catch exceptions of type char*
{
cerr << "Error: " << strException << endl;
}
}
After i run the program, i input a negative number and expected the catch handler to execute and output Error: Can not take sqrt of negative number. Instead the program terminated with the following message
Enter a number : -9
terminate called after throwing an instance of 'char const*'
Aborted
Why was my exception not caught in the catch handler?
You have to add const:
In fact you are throwing
char const *, but expect mutablechar *, which does not match this way (it does the opposite).