开发者

How can I show that method returned successfully or failed without returning a value in C#?

I know in other languages like C/C++ you would return a value like SUCCESS which would indicate to the calling me开发者_开发问答thod that the method returned successfully, or failed.

Is there a "nice" way to do this in C# without needing a SUCCESS return variable? Throwing an exception comes to mind, but I am not sure how one would implement this. Is there a custom exception you could throw with your own error message?

Sample code would be greatly appreciated.

Thank you in advance.


1) I wouldn't recommend using an exception unless the failure was "exceptional." For instance, it failed and that means something that needs to be handled. They are slower than a "false" type return.

2) Why are you trying to avoid a return value? Must you have no return values?


Are you refering to the bool data type?

Example of function definition:

public static bool DoSomething()
{
    if ( some || condition )
        return true;
    else
        return false;
}

Example of usage:

public static void main()
{
    if ( DoSomething() )
        Console.WriteLine( "SUCCESS" );
    else
        Console.WriteLine( "FAILURE" );
}


If your method is void, then the fact that it returned without throwing an exception is considered SUCCESS.

If your method is something other than void, then particular return values might be interpreted as unsuccessful executions, for example:

  • bool method returning false
  • any reference type-returning method returning null


Do not use exceptions for flow control or an indication of a 'success'.

If you want to have an indicator for success or failure in addition to a return parameter, you can use an out bool parameter in your method signature.

public SomeObject DoingSomethingHere(out bool success)
{


}
if (!success)
{
    // some compensating action
}


You can derive your own exceptions from Exception.

You can return a bool or some numeric convention.

In C#, you have output parameters which are a little easier to use than pointers if you want to return success/fail, but also product output.

I tend to go with exceptions for exceptional things. Logical returns for logical things. i.e. Don't use exceptions to control program operations. If a file operation unexpectedly fails, then throw an exception. If the app needs to look for a file and generally expects to not find it sometimes as a normal operation, I would not expect the caller to catch an exception, but instead to simply return a bool and choose an appropriate logical path through the applciation.


It sounds like you want to indicate that a method did not complete successfully without using a return value, or an exception. What about an out bool parameter?

public void Execute(out bool success) {
      try {
          //...
          success = true;
      } catch {
          success = false
      }
}

I would not recommend doing this, but since you asked....


For certain types of failures, a custom exception is certainly a good way to go. One simple approach would be to create a DomainException class (or whatever you want to call it for your application's problem domain, etc.), in a common library, which inherits from Exception and adds any particular information you think would be useful for a custom domain exception. (Maybe specific codes, maybe information about the current environment which may not be available in the standard Exception, etc.)

From there, you can create more specific exceptions which inherit from that, such as DataIntegrityException which can be thrown if, for example, a method receives input which makes sense on a technical level but violates custom business validation rules, etc.


Not throwing an exception would be the way that comes to my mind...

There are basically four ways you can get a message out of a function:

  • return something
  • use an out variable
  • throw an exception
  • set a var to another member of the class

I would throw an exception if something unexpectedly goes wrong. If I expect something not to work all the time, I would use a return value.


You can return a status variable, such as an enumeration, integer or boolean. The trouble is that the caller has to know what different return values mean. Sometimes true means it was successful, sometimes it means there was an error. Also, the immediate caller may not know what to do if the call fails, requiring failures to "bubble up" as each method fails because its call did.

Try-throw-catch is the go-to pattern for handling things you know might fail, and controlling execution flow if/when it does:

public void MightFail()
{
   //obviously your code will do something a little more meaningful
   if(new Random().Next(2) == 0) throw new Exception("I failed");
   return;
}

public void RunRiskyMethod()
{
   var failures = 0;
   var successes = 0;
   var totalRuns = 0;

   for(var i=1;i<10000;i++)
   {
       try
       {
          MightFail();
          //if the previous line throws an exception, the below lines will not execute
          successes++;
          Console.WriteLine("Success!");
       }
       catch(Exception) //I didn't name the exception because we don't need its info.
       {
          //These lines ONLY execute if an exception was thrown from within the try block
          failures++;
          Console.WriteLine("Failure!");
       }
       finally
       {
          //this code ALWAYS executes, even if an exception is thrown and not caught
          totalRuns++;
       }
   }

   Console.WriteLine(String.Format("{0} Successes, {1} Failures.", successes, failures);
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜