在C#程序中,当抛出异常时定义的退出代码是main什么?我知道您可以通过多种方式设置退出代码,如此优秀答案中所述.但是我很惊讶我找不到退出 main时抛出异常的退出代码值的文档.是否有一个标准定义退出代码在这种情况下的价值,或者它取决于操作系统(或机会,或其他任何东西)?
bar*_*lop -2
用户处理它。打开cmd提示符窗口,运行程序yourblahprogram<ENTER>doecho %ERRORLEVEL%
0 表示没有错误。非零表示错误。
我将使用 DIR 但你可以使用你的程序
C:\Users\user\aa\a>dir
Volume in drive C has no label.
Volume Serial Number is B411-D580
Directory of C:\Users\user\aa\a
03/04/2017 11:11 PM <DIR> .
03/04/2017 11:11 PM <DIR> ..
0 File(s) 0 bytes
2 Dir(s) 15,943,544,832 bytes free
C:\Users\user\aa\a>echo %ERRORLEVEL%
0
C:\Users\user\aa\a>dir sdsklfjdlkdfjs
Volume in drive C has no label.
Volume Serial Number is B411-D580
Directory of C:\Users\user\aa\a
File Not Found
C:\Users\user\aa\a>echo %ERRORLEVEL%
1
C:\Users\user\aa\a>
Run Code Online (Sandbox Code Playgroud)
你可以根据它采取行动
C:\Users\user>if NOT ERRORLEVEL 0 echo asdf
Run Code Online (Sandbox Code Playgroud)
虽然实际上上面的方法并不是那么好,因为它只有在错误级别为负数时才能正常工作。因为 NOT ERRORLEVEL 0 意味着不 >=0。正如您从 If /? 看到的那样 并以万无一失的方式检查 Windows 批处理文件中的非零(错误)返回代码
所以如果 errorlevel 不是 0 的话会更好。 IF %ERRORLEVEL% NEQ 0 echo asdf
所以如果你的代码是throw new System.Exception();
C:\Users\user>a.exe
asdf
Unhandled Exception: System.Exception: Exception of type 'System.Exception' was thrown.
at CustomMath.Main()
C:\Users\user>echo %ERRORLEVEL%
-532462766
C:\Users\harvey>
Run Code Online (Sandbox Code Playgroud)
所以你可以据此采取行动。
除了ifWindows cmd批处理脚本中,还有&&和||
假设程序执行 WriteLine("asdf"); 并抛出异常。
这意味着运行 && 左侧的第一件事,如果它没有返回错误,即错误级别 0,则运行右侧的第二件事。所以您会看到第一个示例不运行 echo qwerty,也不显示 qwerty。
C:\Users\user>a.exe && echo qwerty
asdf
Unhandled Exception: System.Exception: Exception of type 'System.Exception' was thrown.
at CustomMath.Main()
Run Code Online (Sandbox Code Playgroud)
现在看第二个例子。|| 是“或”,因此如果左侧或右侧为真,它将运行,但它将是高效的,因此只要其中一侧为真,它就会完成。左侧首先运行,但失败了,因此它继续运行右侧,并将显示 qwerty。
C:\Users\user>a.exe || echo qwerty
asdf
Unhandled Exception: System.Exception: Exception of type 'System.Exception' was thrown.
at CustomMath.Main()
qwerty
C:\Users\user>
Run Code Online (Sandbox Code Playgroud)
因此,您可以使用操作系统来处理它。
在 Linux 上,情况会有所不同,但相似。