[Top][All Lists]
[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]
Errors in TCPStream
From: |
Tommi Mäkitalo |
Subject: |
Errors in TCPStream |
Date: |
Thu, 25 Oct 2001 10:45:21 +0200 |
User-agent: |
Mozilla/5.0 (X11; U; Linux i686; de-AT; rv:0.9.4) Gecko/20010913 |
Hi,
I am working on a FTP-class and use CommonC++ as a base. But I
discovered difficulties catching errors. Here is a example-code:
TCPStream* socket;
try
{
cout << "connecting" << endl;
socket = new TCPStream(InetHostAddress("localhost"), 4711);
cout << "delete" << endl;
delete socket;
cout << "OK" << endl;
}
catch(Socket* s)
{
cerr << "socket error " << s->getErrorNumber() << endl
<< s->getErrorString() << endl;
}
If there is no server listening I should get a SOCKET_CONNECT_FAILED.
But the problem is, that you use the this-pointer in socket-class to
throw the exception. But it isn't valid in the catch-block, because the
constructor isn't fully executed. It makes no difference when I declare
my socket on the stack like this:
try
{
cout << "connecting" << endl;
TCPStream socket(InetHostAddress("localhost"), 4711);
cout << "OK" << endl;
}
catch(Socket* s)
{
cerr << "socket error " << s->getErrorNumber() << endl
<< s->getErrorString() << endl;
}
It is better to create a exception-class and throw that. Maybe you can
derive from std::exception.
Like this:
class SocketException : public std::exception
{
sockerror_t errid;
std::string errstr;
public:
SocketException(sockerror_t err, const char* errs)
: errid(err),
errstr(errs)
{ }
virtual const char* what() const
{ return errstr.c_str(); }
sockerror_t getErrorNumber() const { return errid; }
std::string getErrorString() const { return errstr; }
};
Now this should work:
try
{
cout << "connecting" << endl;
TCPStream socket(InetHostAddress("localhost"), 4711);
cout << "OK" << endl;
}
catch(SocketException s)
{
cerr << "socket error " << s->getErrorNumber() << endl
<< s->getErrorString() << endl;
}
Or even:
try
{
cout << "connecting" << endl;
TCPStream socket(InetHostAddress("localhost"), 4711);
cout << "OK" << endl;
}
catch(exception e)
{
cerr << "exception occured: " << e.what() << endl;
}
By the way, is there a mailing-list for CommonC++ users, where I can
subscribe?
Tommi Mäkitalo
- Errors in TCPStream,
Tommi Mäkitalo <=