Question

My OS is Win8
using Code::Blocks 12.10

I'm trying to get a handle on throwing and handling exceptions using an
example from Starting Out with C++ Early Objects Addison Wesley.

Here is the simple code I'm using:

// This program illustrates exception handling
#include <iostream>
#include <cstdlib>

using namespace std;

// Function prototype
double divide(double, double);

int main()
{
    int num1, num2;
    double quotient;

    //cout << "Enter two integers: ";
    //cin >> num1 >> num2;

    num1 = 3;
    num2 = 0;

    try
    {
        quotient = divide(num1,num2);
        cout << "The quotient is " << quotient << endl;
    }
    catch (char *exceptionString)
    {
        cout << exceptionString;
        exit(EXIT_FAILURE);     // Added to provide a termination.
    }
    cout << "End of program." << endl;
    return 0;
  }

 double divide(double numerator, double denominator)
 {
    if (denominator == 0)
        throw "Error: Cannot divide by zero\n";
    else
        return numerator/denominator;
 }

The program will compile, and when I use two ints > 0 execution is normal. If I try to divide by 0 however, I get the following message:

terminate called after throwing an instance of 'char const*'

This application has requested the Runtime to terminate it in an unusual way.
Please contact the application's support team for more information.

Process returned 255 (0xFF)   execution time : 4.485 s
Press any key to continue.

I've looked at other examples, but have yet to find similar code to derive an answer from.

Any advice?

Was it helpful?

Solution

There's a compelling example in the C++ Standard, [except.throw]/1:

Example:

throw "Help!";

can be caught by a handler of const char* type:

try {
    // ...
} catch(const char* p) {
    // handle character string exceptions here
}

When you throw via throw "Error: Cannot divide by zero\n";, the expression after throw is a string literal, therefore of type array of n const char (where n is the length of the string + 1). This array type is decayed to a pointer [except.throw]/3, therefore the type of the object thrown is char const*.

Which types are catched by a handler (catch) is described in [except.handle]/3, and none of the cases apply here, i.e. the const char* is not catched by a handler of type char*.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top