Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why are unhandled exceptions printed to stderr in .NET/C#?

Tags:

c#

.net

windows

I have a few programs written in C# on Windows and notice that they all will print unhandled exceptions to STDERR. I can't find any documentation on this, what specifically is writing the exception to STDERR? Are there options to enable/disable this or otherwise control how it prints the exception text?

I'm curious as to how reliably a .NET or C# application will print unhandled exceptions to STDERR, maybe a developer can use a compiler or other option to disable that feature completely (something akin to Application.SetUnhandledExceptionMode), or if the program can crash due to an unhandled exception in such a way that it isn't printed to STDERR.

like image 644
Quantic Avatar asked Jan 07 '23 02:01

Quantic


1 Answers

That was nailed down about 45 years ago when Ken Thompson et al created Unix. It was customary to write very small programs that do little things and chain them one after the other. Redirecting the output of one program as the input of the next.

One thing that doesn't work that well when you do this is when one of those programs fails. Sending error text to the next program would just make it fail in a completely undiagnosable way. So another output stream was needed that could display error messages to the terminal. Like "Not a bicycle" :) Thus the distinction between stdout and stderr.

Windows had to adopt a very similar approach to be at least a little compatible with a lot of existing software. The console is an emulation of the terminals of old. Accordingly, .NET writes exception messages to stderr. Painful btw, many a .NET programmer has floundered at ProcessStartInfo.RedirectStandardXxx. Which often fails because they forget to redirect stderr or creates deadlock because the program first reads stdout and then stderr. The text encoding disaster (consoles can only support 8-bit encoding) was another consequence.

like image 104
Hans Passant Avatar answered Jan 14 '23 12:01

Hans Passant