简体   繁体   English

在C#中,您可以从main返回默认的int值吗?

[英]In C# can you return a default int value from main?

I want to return a default int value from main. 我想从main返回默认的int值。

Consider the following: 考虑以下:

using System;
class Class1
{
    static int Main(string[] args)
    {
        int intReturnCode = 1;
        int intRandNumber;

        Random myRandom = new Random();
        intRandNumber = myRandom.Next(0,2);
        if(intRandNumber ==1)
        {
            throw new Exception("ErrorError");      
        }
        return intReturnCode;
    }
}

When the exception is reached I don't get to set the returncode. 到达异常时,我无法设置返回码。

Is it possible to have a default return code inside of main? 是否可以在main内部使用默认的返回码?

Clarification: I have a program that is throwing Unhandled Exceptions. 澄清:我有一个程序引发未处理的异常。 I have the application inside a try catch, however some errors (probably out of memory, stackoverflow etc) are still bubling up and causing my application to fail in production. 我将应用程序置于try catch中,但是某些错误(可能是内存不足,stackoverflow等)仍然冒泡并导致我的应用程序在生产中失败。

To fix this I've added code to capture unhandled exceptions. 为了解决这个问题,我添加了代码来捕获未处理的异常。

This was added to main: 这被添加到主要:

AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(OnUnhandledException);

And now I have this method that is reached when an unhandled exception occurs. 现在我有了未处理的异常发生时可以到达的此方法。

public static void OnUnhandledException(object sender, UnhandledExceptionEventArgs e)   
{ 
    //here's how you get the exception  

    Exception exception = (Exception)e.ExceptionObject;                 

    //bail out in a tidy way and perform your logging
}

The prblem is that I'm no longer in Main and I want to exit with a non-zero exit code. 问题是我不再在Main中了,我想退出时使用非零退出代码。

An unhandled exception is implementation defined behaviour . 未处理的异常是实现定义的行为 Anything can happen; 任何事情都可能发生; the CLR can decide to set the return code of the process as it sees fit, it can start a debugger, it can do whatever it wants. CLR可以决定设置它认为合适的过程的返回码,可以启动调试器,可以执行所需的任何操作。 You cannot rely on any behaviour of any program that contains an unhandled exception. 您不能依赖任何包含未处理异常的程序的行为。

If you want to have predictable behaviour, like determining what the return code is when the process ends, then there must be a total of zero unhandled exceptions. 如果您希望具有可预测的行为,例如确定流程结束时返回的代码,那么总共必须有零个未处理的异常。

If you have a third party component that is throwing unhandled out of memory exceptions then your best bet is: fix the bug in that component . 如果您有第三方组件抛出未处理的内存异常,那么最好的选择是: 修复该组件中的错误 If you can't do that then isolate the component into its own process or its own appdomain . 如果不能这样做,则将组件隔离到其自己的进程或自己的appdomain中

The question is really why you are throwing an exception in main instead of providing a return code that indicates an error? 真正的问题是,为什么要在main引发异常而不是提供指示错误的返回码? Instead of what you're doing, my code would look as follows: 代替您在做什么,我的代码如下所示:

static int Main(string[] args)
{
    int intRandNumber;

    try
    {
        Random myRandom = new Random();
        intRandNumber = myRandom.Next(0,2);
        if(intRandNumber ==1)
        {
            Console.WriteLine("Got invalid random number!");
            return 0;
        }
    }
    catch (Exception exp)
    {
        Console.WriteLine("Strange ... an error occurred! " + exp.ToString());
        return -1;
    }

    return 1;
}

As a rule of thumb you should never throw exceptions to control program flow. 根据经验,永远不要抛出异常来控制程序流。 If you can, handle conditions like oops, I got the wrong number without throwing an exception. 如果可以的话,可以处理类似oops的情况,那么我得到的错误数字没有引发异常。

Throwing an exception in the main thread ends execution without reaching the return : that's when you get the "Console application has stopped working, would you like to debug?" 在主线程中引发异常将结束执行而未return :那就是当您收到“控制台应用程序已停止工作,您要调试吗?” dialog from the operating system. 操作系统中的对话框。 The Main cannot return anything under these conditions, because there is nothing to return. 在这种情况下, Main不能返回任何东西,因为没有任何东西可以返回。

If you would like to return something when you get an exception, code your program like this: 如果您想在遇到异常时返回某些信息,请对程序进行如下编码:

// Put your implementation into a private method
private static int DoWork(string[] args) {
    ... // Do actual work, and throw exceptions if you need to
    return intReturnCode;
}
// The Main method calls the implementation, and returns the value
// returned from the implementation if everything goes well.
// If an exception is thrown, however, Main could return another value
// of its choice.
public static int Main(string[] args) {
    try {
        return DoWork(args);
    } catch {
        return myDefaultReturnCode;
    }
}

catch your exception and set return statement in finally block 捕获您的异常并在finally块中设置return语句

using System;
class Class1
{
    static int Main(string[] args)
    {
        try
        {
            int intReturnCode = 1;
            int intRandNumber;

            Random myRandom = new Random();
            intRandNumber = myRandom.Next(0,2);
            if(intRandNumber ==1)
            {
                throw new Exception("ErrorError");      
            }
        }
        catch(Exception e)
        {
          // ...
        }
        finally
        {
            return intReturnCode;
        }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM