Quit the program when catching error in C#?
Solution 1
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>
}
}
}
Solution 2
Normally, you simply don't catch exceptions you can't handle. .NET takes care of killing your process for you.
prosseek
A software engineer/programmer/researcher/professor who loves everything about software building. Programming Language: C/C++, D, Java/Groovy/Scala, C#, Objective-C, Python, Ruby, Lisp, Prolog, SQL, Smalltalk, Haskell, F#, OCaml, Erlang/Elixir, Forth, Rebol/Red Programming Tools and environments: Emacs, Eclipse, TextMate, JVM, .NET Programming Methodology: Refactoring, Design Patterns, Agile, eXtreme Computer Science: Algorithm, Compiler, Artificial Intelligence
Updated on June 01, 2021Comments
-
prosseek almost 3 years
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()?