This is the mail archive of the
gcc-help@gcc.gnu.org
mailing list for the GCC project.
Re: throw <const string>
- From: Miguel Ramírez <mramirez at iua dot upf dot es>
- To: "thomas joseph" <thomascanny at yahoo dot co dot nz>,<gcc-help at gcc dot gnu dot org>
- Date: Mon, 18 Nov 2002 10:14:43 +0100
- Subject: Re: throw <const string>
- References: <20021118054259.88967.qmail@web14704.mail.yahoo.com>
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.