我想从 main 返回一个默认的 int 值。
考虑以下:
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;
}
}
遇到异常时,我无法设置返回码。
是否可以在 main 中有默认返回码?
澄清:我有一个抛出未处理异常的程序。我在 try catch 中有应用程序,但是一些错误(可能内存不足、stackoverflow 等)仍在冒泡并导致我的应用程序在生产中失败。
为了解决这个问题,我添加了代码来捕获未处理的异常。
这被添加到主要:
AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(OnUnhandledException);
现在,当发生未处理的异常时,我有了这个方法。
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
}
问题是我不再在 Main 中,我想以非零退出代码退出。