Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Quit the program when catching error in C#?

Tags:

c#

exception

exit

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()?
like image 738
prosseek Avatar asked Feb 11 '11 17:02

prosseek


People also ask

What is exit () function in C?

The exit () function is used to break out of a loop. This function causes an immediate termination of the entire program done by the operation system. The general form of the exit() function is as follows − void exit (int code);

How do I stop a program in C?

So the C family has three ways to end the program: exit(), return, and final closing brace.

What does exit 0 do in C?

exit is a jump statement in C/C++ language which takes an integer (zero or non zero) to represent different exit status. Exit Success: Exit Success is indicated by exit(0) statement which means successful termination of the program, i.e. program has been executed without any error or interrupt.

Where is exit () defined?

The function has been defined under the stdlib. h header file, which must be included while using the exit() function.


1 Answers

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>
        }
    }
}
like image 131
Baltasarq Avatar answered Sep 23 '22 20:09

Baltasarq