[英]In C# can you return a default int value from main?
我想从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中了,我想退出时使用非零退出代码。
未处理的异常是实现定义的行为 。 任何事情都可能发生; CLR可以决定设置它认为合适的过程的返回码,可以启动调试器,可以执行所需的任何操作。 您不能依赖任何包含未处理异常的程序的行为。
如果您希望具有可预测的行为,例如确定流程结束时返回的代码,那么总共必须有零个未处理的异常。
如果您有第三方组件抛出未处理的内存异常,那么最好的选择是: 修复该组件中的错误 。 如果不能这样做,则将组件隔离到其自己的进程或自己的appdomain中 。
真正的问题是,为什么要在main
引发异常而不是提供指示错误的返回码? 代替您在做什么,我的代码如下所示:
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;
}
根据经验,永远不要抛出异常来控制程序流。 如果可以的话,可以处理类似oops的情况,那么我得到的错误数字没有引发异常。
在主线程中引发异常将结束执行而未return
:那就是当您收到“控制台应用程序已停止工作,您要调试吗?” 操作系统中的对话框。 在这种情况下, Main
不能返回任何东西,因为没有任何东西可以返回。
如果您想在遇到异常时返回某些信息,请对程序进行如下编码:
// 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;
}
}
捕获您的异常并在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.