我想从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;
}
}
Run Code Online (Sandbox Code Playgroud)
达到异常时,我无法设置返回码.
是否有可能在main中有一个默认的返回码?
澄清:我有一个程序正在抛出未处理的异常.我在try catch中有应用程序,但是一些错误(可能是内存不足,stackoverflow等)仍在冒泡并导致我的应用程序在生产中失败.
为了解决这个问题,我添加了代码来捕获未处理的异常.
这被添加到main:
AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(OnUnhandledException);
Run Code Online (Sandbox Code Playgroud)
现在我有一个未处理的异常发生时达到的方法.
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
}
Run Code Online (Sandbox Code Playgroud)
问题是我不再在Main中,我想退出非零退出代码.
未处理的异常是实现定义的行为.任何事情都可能发生; CLR可以决定在它认为合适时设置进程的返回代码,它可以启动调试器,它可以做任何想做的事情.您不能依赖任何包含未处理异常的程序的任何行为.
如果您希望具有可预测的行为,例如确定流程结束时返回代码的内容,则必须总共有零个未处理的异常.
如果你有第三方组件抛出未处理的内存异常,那么最好的办法是:修复该组件中的错误.如果您不能这样做,那么将组件隔离到自己的进程或自己的appdomain中.
| 归档时间: |
|
| 查看次数: |
449 次 |
| 最近记录: |