6

I am trying to catch a char * type exception in main() but the program crashes with the following message: terminate called after throwing an instance of 'char const*' Here is the code:

#include <iostream>

int main ()
{
    char myarray[10];
    try
    {
        for (int n=0; n<=10; n++)
        {
            if (n>9)
            throw "Out of range";
            myarray[n]='a';
        }
    }
    catch (char * str)
    {
        std::cout << "Exception: " << str << std::endl;
    }
    return 0;
}

5 Answers 5

14

Use const:

catch (const char * str)
    {
        std::cout << "Exception: " << str << std::endl;
    }
1
  • 6
    This is actually the correct answer. A string literal is const, so needs to be caught as such. The other answers (about constructing and throwing std::exception or derived types) are good style, but answer a different question.
    – Peter
    Commented Oct 29, 2015 at 9:52
4

You don't want to catch char*.

I don't know where this idea comes from that string literals are char*: they're not.

String literals are const char[N] which decays to const char*.

Catch const char*.

Your program is being terminated because, at present, you're actually not handling your exception!

3

Prefer an exception:

try {
    for (int n=0; n<=10; n++) {
        if (n>9) throw std::runtime_error("Out of range");
        myarray[n]='a';
    }
} catch (std::exception const& e) {
    std::cout << "Exception: " << e.what() << std::endl;
}
2
  • If l try to throw an int l cannot catch it either Commented Oct 29, 2015 at 9:47
  • 2
    You did not answer the question. Commented Oct 29, 2015 at 10:50
1

The C++ Standard library provides a base class specifically designed to declare objects to be thrown as exceptions. It is called std::exception and is defined in the header. This class has a virtual member function called what that returns a null-terminated character sequence (of type char *) and that can be overwritten in derived classes to contain some sort of description of the exception.

// using standard exceptions
#include <iostream>
#include <exception>
using namespace std;

class myexception: public exception
{
  virtual const char* what() const throw()
  {
    return "My exception happened";
  }
} myex;

int main () {
  try
  {
    throw myex;
  }
  catch (exception& e)
  {
    cout << e.what() << '\n';
  }
  return 0;
}

For more help: http://www.cplusplus.com/doc/tutorial/exceptions/

1
-4

You cannot throw a string like that, you need to create an object.

Replace throw "Out of range" by throw std::out_of_range("Out of range")

Regards,

1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.