Essentially, I'd like a special form of an Interface
for Exceptions that requires anyone who uses my object to wrap it with specific catch
implementations.
Example
I have an object that sends data to another host. I expect that the realistic implementations will require a way to handle the following exceptions:
Similar to how an Interface
or an Abstract
class is used to force the creation of methods and properties in derived classes, is there any way I can force a consumer to implement exception handling the way I expect?
On a similar note, I'd also like to force methods (created via Interface or Abstract) to be able to generate certain exceptions. Sure they may be NotImplemented, but I want to tell that developer (who doesn't read documentation) that they should be considered.
Goal
The benefit of this exception checking is to enable more robust error handling. This would be accomplished by the consumer using the object, and the object creator.
Solution?
The only approach I can think of is T4 templates, but that isn't as complete of a solution as I would like. I'd love to see this implemented in the language itself.
You can't force a programmer to do anything except jump through hoops. For example, let's say you have some method called Frob
that does something, and can throw FrobinatorException
. You expect programmers to write:
try
{
var result = Frob(foo);
}
catch (FrobinatorException)
{
// handle exception here
}
But you find that they don't. So force them to by defining Frob
like this:
public FrobResult Frob(FrobyThing foo, Action FrobinatorExceptionHandler);
And then programmers have to write something like:
var result = Frob(
foo,
() => { /* handle FrobinatorException here */; });
Programmers will grumble about having to do that and they'll end up writing this:
var StupidExceptionHandler = new Action(() => {});
var result = Frob(foo, StupidExceptionHandler);
And now you're worse off than you were because the exceptions are being swallowed, which hides bugs. It's better if the programmer just ignores the exception handling altogether. At least that way you know when an error occurs.
There's simply no way to force good exception handling. At least, not in C# as it currently exists. You can make it more convenient to handle exceptions, but doing so often makes it easier to hide exceptions by swallowing them.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With