Q:

Dealing with specific exceptions

I have a piece of network code that throws various exception which are all caught under a general catch exception statement.
try {
    network code
} catch (Exception e) {
    freeaddrinfo(some_address);
}

The problem with this method is the freeaddrinfo within the exception. Not all cases of exception can/should call freeaddrinfo and in my specific case freeaddrinfo should not be called when there is an invalid address that is passed into the network code to connect somewhere. My idea of solving this problem is to retrieve the error code that was thrown by this exception and to possibly use this in combination with e.to_string to deal with this edge case. From what I have learned from Effective Java, this is a fragile way of dealing with this problem. What do you recommend I should do?

A:

In C++, the usual way to release a resource after an exception is not to catch the exception, but to wrap the resource in an object whose destructor is responsible for releasing. That way, it is released when the management object goes out of scope (or is otherwise destroyed), whether or not an exception is thrown. This technique is known as RAII.
A (very basic) management object might look like:
struct AddressInfo {
    addrinfo * info;

    // Constructor takes ownership of resource
    explicit AddressInfo(addrinfo * info) : info(info) {}

    // Destructor releases resource
    ~AddressInfo() {freeaddrinfo(info);}

    // Prevent shallow copying, so only one object manages the resource
    AddressInfo(AddressInfo const &) = delete;
    void operator=(AddressInfo const &) = delete;
};

Then your code would become:
// some network code
AddressInfo address(some_address);
// some more network code

with no need for any exception handling or manual clean-up code.

