Z
Zork
Hi,
I am trying to stop object creation (in this case ill use a ball as the
object) via use of exceptions. In essence, if the ball does not have an
owner, I do not want the ball object created. Here is my program sketch:
-------------------------
#include <sstream>
class NullOwnerException : public exception
{
public:
NullOwnerException::NullOwnerException() : exception ( "A NULL owner was
found" ) {}
};
// Ball constructor
Ball :: Ball ( Owner * o, string c, double r )
{
if ( ! o ) throw NullOwnerException(); // the ball does not have an owner
Owner = o;
Color = c;
Radius = r;
}
..
..
int main ( void )
{
Owner o1 = Owner("John");
Ball b1;
try { b1 = Ball(&o1, "Blue", 10.3); }
catch ( NullOwnerException & nullOwnerException )
{cout << nullOwnerException.what() << endl ; }
}
----------------------
Now the above works fine, but the question is, is there any way of hiding
the try{}catch(){} from the main(void) ? I was hoping of just having a clean
main as follows:
int main ( void )
{
Owner o1 = Owner("John");
Ball b1= Ball(&o1, "Blue", 10.3);
}
Maybe the constructor itself can handle the exception? I do not want to use
a factory method.
Thanks for any help!
Zork
I am trying to stop object creation (in this case ill use a ball as the
object) via use of exceptions. In essence, if the ball does not have an
owner, I do not want the ball object created. Here is my program sketch:
-------------------------
#include <sstream>
class NullOwnerException : public exception
{
public:
NullOwnerException::NullOwnerException() : exception ( "A NULL owner was
found" ) {}
};
// Ball constructor
Ball :: Ball ( Owner * o, string c, double r )
{
if ( ! o ) throw NullOwnerException(); // the ball does not have an owner
Owner = o;
Color = c;
Radius = r;
}
..
..
int main ( void )
{
Owner o1 = Owner("John");
Ball b1;
try { b1 = Ball(&o1, "Blue", 10.3); }
catch ( NullOwnerException & nullOwnerException )
{cout << nullOwnerException.what() << endl ; }
}
----------------------
Now the above works fine, but the question is, is there any way of hiding
the try{}catch(){} from the main(void) ? I was hoping of just having a clean
main as follows:
int main ( void )
{
Owner o1 = Owner("John");
Ball b1= Ball(&o1, "Blue", 10.3);
}
Maybe the constructor itself can handle the exception? I do not want to use
a factory method.
Thanks for any help!
Zork