C ++ - Some Questions About Launching Exceptions

advertisements

I've got a few questions about throwing exceptions in C++. From what I know about them...

An exception can be thrown from within the main() function. Any block of code that can throw an exception in the main() function should be surrounded by try and catch statements as follows

    void foo(//args) {
     if (...) {
      throw "Error reached";
     } ...

    int main() {
     ...
     try {
      //Code that can throw an excpetion
     } catch(const char* msg) (
      cerr << msg << endl;
     }
     ...
    }

In the example above, why is the argument to the catch a const char *. Doesn't C++ allow for strings? Also, is it possible to throw an exception that isn't a const char *, like an int? or a char?

Does throwing an exception in foo, terminate the foo function?

Are there cases where you could put the try and catch statements in the same function as the throw?

Sorry if these are basic questions. Thanks SO


why is the argument to the catch a const char *

Because you threw string literal which decays to const char*. In short, you catch what you throw.

Doesn't C++ allow for strings?

It does, but to catch string, you need to throw string in first place.

is it possible to throw an exception that isn't a const char *,

You can throw literally anything. It is a good idea to throw special exception classes, like std::exception and derived from it.

Does throwing an exception in foo, terminate the foo function?

Yes, it does.

Are there cases where you could put the try and catch statements in the same function as the throw?

If you want, you can do that. There are not much cases where doing it is a good idea.

It looks like you need to get a good book and read chapter about exceptions. In the meantime this super-FAQ entry might help you/