Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

I am creating an interface and would like the implementer(s) of this interface t

ID: 644490 • Letter: I

Question

I am creating an interface and would like the implementer(s) of this interface to throw exceptions in the case that something goes wrong. Let's call the implementer a plugin. I have a director which can call any one of the plugins. Rather than each plugin throwing it's own random exception, I would like plugins to throw specific exceptions which my director can then handle. For example: If the plugins fail to authenticate with the credentials that are provided by the director or if the requested action times out on the plugin, the plugin should throw an exception. Rather than each plugin throw it's own random exception, I would like plugins to throw specific exceptions that the director knows about and can handle. I do this because if an exception is fatal (like authentication failed) I don't want to retry, whereas if it was a timeout, the director may decide to retry.

Now, I am confused as to which of the following ways is better:

Idea 1:

Create a custom exception (lets say PluginException) and have an enum type which different types of exception (such as authenticationfailed, timeoutout, permissiondenied, etc.) The director will catch all PluginExceptions and handle each exception case by case.

Idea 2:

Create an abstract exception (lets say PluginException again) and have specific exception types derive from my abstract exception (like AuthenticationFailedException, TimeoutException, etc.) The director can listen for any specific exception it is interested in and also listen for the broader PluginException if none of the above exception types match the exception thrown by the plugins.

Explanation / Answer

The main problem you'll have here is that C# has no way of enforcing your exception types among implementers.

The bigger problem for me is that this implies that your plugins are very closely coupled to your director. I would normally expect a simple API for communication between the plugin and director. Then too, this custom exception could run code when thrown, which to my naive sensitivities would appear to be a potential security threat.

Ultimately, I'd say that timeouts and authentication issues are owned by the code that attempts them. You don't trust a plugin to tell you it's authentication failed, you simply fail to authenticate the plugin. If a plugin times out, it lies on the implementer to solve it. I find it likely that you do not want or need this kind of crosstalk in your application.