5

With Python, I normally check the return value. And, if there's an error, I use sys.exit() together with error message.

What's equivalent action in C#?

  • Q1 : How to print out an error message to stderr stream?
  • Q2 : How to call system.exit() function in C#?
  • Q3 : Normally, how C# programmers process the errors? Raising and catching exceptions? Or, just get the return value and exit()?

2 Answers 2

7

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.

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

Q2: You exit with:

System.Environment.Exit( exitCode );

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.

If you want to catch errors in the entire program, you just encapsulate the entire main() procedure in a 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>
        }
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

Please do not use System.Environment.Exit. Sure it's cool you can kill your app whenever you want but doing so makes automated testing of your code more difficult than it needs to be.
3

Normally, you simply don't catch exceptions you can't handle. .NET takes care of killing your process for you.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.