开发者

Specifying that a function does not return in C#

Is there any way to tell the C# compiler that a function never returns? I'm running into the following problem. This is a boiled down version for simplicity.

public int myMethod()
{
    try
    {
        return anythingHere();
    }
    catch
    {
        Environment.Exit(1); //or a function which always either calls Environment.Exit or throws an exception
    }
}

'package.class.myMethod()' not all 开发者_StackOverflowcode paths return a value.

If not, is there a general way to frame this sort of thing other than inserting unreachable code? Having a 'return 0' or somesuch after the Exit just seems ridiculous to me. As far as I know there is no way that a function can return from an Environment.Exit call, so no return value is needed if that branch is taken (if it threw an exception the function still wouldn't need to have returned a value).

EDIT:

Maybe something like this?

public T MyExit<T>()
{
    Environment.Exit(1);
    return default(T);
}

Still not entirely satisfactory though.


C# does not support this.

In fact, it is impossible to do this in the general case.


Make the method void, and pass in an object that contains the 'anythingHere' type of information you need as an out type, so that it can be set, but the method itself won't actually return anything.

public void myMethod(out anythingObject)
{
    try
    {
        anything = new anythingObject(stuff goes here); 
    }
    catch
    {
        Environment.Exit(1); //or a function which always either calls Environment.Exit or throws an exception
    }
}


I'm not sure if it's what you're looking for, but this would avoid unreachable code:

public int myMethod()
{
  int retVal = 0;
  try {
    retVal = anythingHere();
  } catch {
    Environment.Exit(1);
  }
  return retVal;
}


It might be better to throw an exception than to call Environment.Exit. If someone else used your class, and their process suddenly shut down, they'd be pretty surprised. By throwing an exception you can at least explain why the problem happened.

At the top level entry point of your app (i.e., Main) you could then set up a global exception handler (AppDomain.UnhandledException) that handles all exceptions and calls Environment.Exit.


Make it a void, instead of an int.

public void myMethod(out int i)
{
    try
    {
       i = anythingHere();
    }
    catch
    {
        Environment.Exit(1);
    }
}
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜