Question

I am creating a "Common" library to be used as reference in various solution projects by other team members. The methods are typically void functions with no actual returned data.

I am looking for a why to force the usage of these methods within a Try...Catch block by others. I need to make sure errors are properly handled. I though about relying on a Boolean return type but that will not allow me to return the error message as well, so my only option is throwing an Exception.

If proper forcing is not possible, how can I make an attribute that pops-up when compiling to warn the developer about the Try/Catch requirement? (sort of the Obsolete attribute).

Any other better approaches?

EDIT:

Here is my full scenario:

I have a code method calling a web service to update a value remotely. The update is quite crucial. The method it self works fine but what if the web service is not reachable? The call does not return any value.

Was it helpful?

Solution

Placing something inside a try/catch block does not make it "properly handled" - in fact, in the vast majority of cases, the correct way of handling an exception is to let it bubble up to the next level. Caveat: try/finally is much more common, to allow for resource clean-up, but even more common than that is using.

You cannot enforce "and you must use it correctly" on code; that is implicit in any API, and you will just be causing irritation and annoyance, and forcing people into inappropriate and unhelpful coding styles, while giving you a completely artificial and incorrect sense of the code being correct.

If you want to be sure that the code functions correctly: test it.

There are no attributes that you can use for this scenario. You can probably create an FxCop rule or similar, but for the reasons above: I do not recommend it.

OTHER TIPS

I wouldn't actually do this, but as a fun solution to the stated problem you could build your own Exception type: a SuccessException. Then, you throw this exception at the end of your method to indicate success. This makes the method pretty much unusable without some form of try/catch. But, again: don't do this.

You could return a custom result class:

public class Result
{
    public bool Okay { get; set; }
    public string Error { get; set; }
}

Then:

var result = AttemptSomething();

if (!result.Okay)
{
    Console.WriteLine(result.Error);
}

Or maybe return string:

var error = AttemptSomething();

if (!String.IsNullOrEmpty(error))
{
    Console.WriteLine(error);
}

Or have the error as an out:

string error;
if (!AttemptSomething(out error))
{
    Console.WriteLine(error);
}

Or return Exception but don't throw.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top