This is the mail archive of the gcc-help@gcc.gnu.org mailing list for the GCC project.


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]
Other format: [Raw text]

Re: throw <const string>


Hi,

>
> Hi All,
>  I am trying a sample with c++ exception handling.
>  Could you tell me the point in the following code.
>
> #include <iostream>
> using namespace std;
> int main()
> {
>     char *buf = "Memory allocation failed!";
>
>     try
>     {
>            throw "Memory allocation failure!";
>           //  throw buf;
>     }
>     catch( char *str)
>     {
>         cout << "Exception raised: " << str << '\n';
>     }
>      return 0;
> }
>

C++ exceptions are objects:

#include <exception>

class MyCustomException : public std::exception
{
public:

const char* what()
{
    return " Memory Allocation failure";
}

};

so you can now

 #include <iostream>
#include "MyCustomException.hxx"
 using namespace std;
 int main()
 {
     try
     {
            throw "Memory allocation failure!";
           //  throw buf;
     }
     catch( std::exception& e )
     {
         cout << "Exception raised: " << e.what( ) << '\n';
     }
      return 0;
 }

Note that there are already many exceptions classes available in the
standard library,
so this example is kind of "rash". Well, it may be quite a pain in the back
to take account
of the standard exception class hierarchy, but it may pay out in the long
term.

Miguel Ramírez.

PS: Note that new already launches an exception when memory allocation fails
unless
you use the std::no_throw variant.


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]