Network connection setup in constructor: good or bad?

c++, network-programming

Solution

I consider it bad to do a blocking `connect()` in a constructor, because the blocking nature is not something one typically expects from constructing an object. So, users of your class may be confused by this functionality.

As for exceptions, I think it is generally best (but also the most work) to derive a new class from std::exception. This allows the catcher to perform an action for that specific type of exception with a `catch (const myexception &e) {...}` statement, and also do one thing for all exceptions with a `catch (const std::exception &e) {...}`.

See related question: How much work should be done in a constructor?

Problem

I'm working on a class that handles interaction with a remote process that may or may not be available; indeed in most cases it won't be. If it's not, an object of that class has no purpose in life and needs to go away. Is it less ugly to: - Handle connection setup in the constructor, throwing an exception if the process isn't there. - Handle connection setup in a separate `connect()` method, returning an error code if the process isn't there. In option 1), the calling code will of course have to wrap its instantiation of that class and everything else that deals with it in a `try()` block. In option 2, it can simply check the return value from connect(), and return (destroying the object) if it failed, but it's less RAII-compliant, Relatedly, if I go with option 1), is it better to throw one of the std::exception classes, derive my own exception class therefrom, roll my own underived exception class, or just throw a string? I'd like to include some indication of the failure, which seems to rule out the first of these. Edited to clarify: The remote process is on the same machine, so it's pretty unlikely that the `::connect()` call will block.

Original source

Related problems