I ran into an annoying problem the other day when working with a 3rd party library, mail.dll. You see, mail.dll exposes library methods for sending email messages to an SMTP server, functionality common enough that you should never have to write it yourself. While I’ve been pleased with its ability to perform SMTP conversations, I have not been impressed with its use of exceptions.
When the mail.dll SMTP library fails to connect or get a response from the SMTP server to which it is connecting, it throws a mail.dll-specific custom exception, SmtpResponseException. Likewise for the IMAP and POP3 libraries, if a failure happens during client interaction with the server, an ImapResponseException or Pop3ResponseException is thrown, respectively. Since, in the normal course of a properly configured mail client’s operation, the expectation is that the server will respond appropriately, I don’t have a problem with these libraries throwing exceptions. They are understood and can be handled by the consuming application.
Here’s the annoying bit. The custom exceptions thrown by mail.dll only have internal constructors and cannot be thrown outside of the mail.dll assembly. In this article, I’ll talk about why your library should not throw exceptions that the consuming code cannot throw itself and a workaround when someone else’s library does.