I wrote a C++ demo
test.cpp
int main()
{
int num = 1 / 0;
}
$ g++ test.cpp -o test
$ ./test 2>error.txt
Floating point exception (core dumped)
Because the error message is not generated by the program. It is generated by the operating system.
Think: the program has died already. How can it generate extra output?
In fact, you'll observe output even if you redirect both stdout and stderr of the program to /dev/null
.
If you create a sub-shell and redirect its stderr, you'll see the error message redirected:
( ./test ) 2>error.txt