Re: [Dev-C++] Constructors throwing exceptions.
Open Source C & C++ IDE for Windows
Brought to you by:
claplace
|
From: Abhijit S. <mu...@gm...> - 2002-07-25 18:00:19
|
----- Original Message -----
From: "Daniel Glenfield" <sp...@ho...>
To: <dev...@li...>
Sent: Tuesday, July 23, 2002 6:22 PM
Subject: [Dev-C++] Constructors throwing exceptions.
> Hello all,
> I want my constructors (default, overloaded, and copy) to throw an
> exception if they fail.
>
> 1) How do I test if the constructor has failed?
--------------Start--------------------
#include <iostream>
using std::cout;
using std::endl;
class foo
{
public:
foo()
{
throw "bar";
}
};
int main()
{
try
{
foo baz;
}
catch(const char *err)
{
cout << "I caught\"" << err << "\" from foo" << endl;
}
return 0;
}
--------------Stop------------------
> 2) Is it better to create an Exception class to throw exception objects,
> rather than throwing strings and integers?
I think it's better to have objects, so you can easily upgrade the
error-handling capabilties of the program. This way, you can also have
different attributes to an error (fatal/non-fatal, etc.) You can also make
the error class have functions like do_what_you_have_to(), which can do what
it has to (fatal errors exit, non-fatals drop a log and print a message)
> 3) Where does the catch block go? In the main function after the object
has
> been created? Or in the constructor body?
Whenever you throw something, a new object 'something' is created and
dispatched to the catch{} block. This object's scope is similar to that of
an object returned by the function. You can have any number of nested
levels, as long as the level which is throw()ing is within a try{}. So you
can have
void baz()
{
throw new AnException("yeeppep", 23);
}
void bar()
{
baz();
}
void foo()
{
bar();
}
try
{
foo();
}
catch(AnException my_very_own)
{
// whatever
// delete my_very_own;
}
If I typed something wrong (grammatical, not technical... no wait, maybe
that too :), excuse me... I'm so friggin' sleepy. G'night to you all.
|