I want to capture an error message so I can print it out later. For exmaple, I can capture the the error message for division by zero in the following by setting myerror equal to the $MessageList as long as it is on the same line, apparently. And by repeating myerror on the next line, the output proves that I have captures the “Power::infy” error message. But the specific error statement “Infinite expression 1/0 encountered. >>” I don’t know how to capture.
Your comment on another post is a separate question and it was re-posted as a new discussion. Please in future do not ask new questions on existing discussions but submit them as new. Also note code-box formatting and please follow it in future.
One way would be to add your own output stream to $Messages, which is a list that holds the output streams that messages are written to. Normally $Messages is a list of one output stream, namely the standard output stream (stdout). So this opens an output stream and appends it to $Messages:
The HoldForm is required in messages, to avoid an infinite recursion (and InputForm always displays HoldForm as is).
If you don’t like the HoldForm, you could convert the HoldForm to a string and remove that: