简体   繁体   English

在C#中捕获错误时退出程序?

[英]Quit the program when catching error in C#?

With Python, I normally check the return value. 使用Python,我通常会检查返回值。 And, if there's an error, I use sys.exit() together with error message. 并且,如果有错误,我将sys.exit()与错误消息一起使用。

What's equivalent action in C#? C#中的等效动作是什么?

  • Q1 : How to print out an error message to stderr stream? Q1:如何将错误消息打印到stderr流?
  • Q2 : How to call system.exit() function in C#? Q2:如何在C#中调用system.exit()函数?
  • Q3 : Normally, how C# programmers process the errors? 问题3:通常,C#程序员如何处理错误? Raising and catching exceptions? 提高和捕捉异常? Or, just get the return value and exit()? 或者,只需获取返回值并退出()?

Q1: In C#, you have to use System.Console.xxx in order to access the streams for input, output, and error: System.Console.Error is the standard error you can write to. Q1:在C#中,您必须使用System.Console.xxx才能访问输入,输出和错误的流:System.Console.Error是您可以写入的标准错误。

http://msdn.microsoft.com/en-us/library/system.console.aspx http://msdn.microsoft.com/en-us/library/system.console.aspx

Q2: You exit with: Q2:退出时:

System.Environment.Exit( exitCode );

http://msdn.microsoft.com/en-us/library/system.environment.exit.aspx http://msdn.microsoft.com/en-us/library/system.environment.exit.aspx

Q3: Yes, C# programmers raise (throw) exceptions (objects of classes deriving from the Exception class), and catch them in upper-level callers. Q3:是的,C#程序员引发(抛出)异常(派生自Exception类的类的对象),并在高级调用者中捕获它们。

If you want to catch errors in the entire program, you just encapsulate the entire main() procedure in a try...catch: 如果你想在整个程序中捕获错误,你只需将整个main()过程封装在try ... catch中:

class App {
    public static void Main(String[] args)
    {
        try {
            <your code here>
        } catch(Exception exc) {
            <exception handling here>
        }
        finally {
            <clean up, when needed, here>
        }
    }
}

Hope this helps. 希望这可以帮助。

Normally, you simply don't catch exceptions you can't handle. 通常,您根本不会捕获无法处理的异常。 .NET takes care of killing your process for you. .NET会为您处理您的进程。

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

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