I got a random error message.

expr = N[Pi, a]
expr = Sin[x,

enter image description here enter image description here

The error message does not appear in the 'Output Cell'.

In : msg = "How do I write the code?" 
            However, you must write the code using only 'expr' or 'N[Pi,a]'
Out : "N::precbd :: Requested precision a is not a machine-sized real number
                    between $MinPrecision and $MaxPrecision." 

I want to assign an error message to the symbol and continue the additional work. What should I do?


3 Answers 3


The typical way to "capture" errors is with Check:

expr = Check[N[Pi, a], "the result if fail"]

If N[Pi, a] generates any messages, then expr will be set to "the result if fail". So, you can create whatever failure result you want and do subsequent processing with it.

  • $\begingroup$ Can't you express it with the error message above instead of "the result if fail"? $\endgroup$
    – Milk
    Nov 19, 2023 at 22:51
  • 1
    $\begingroup$ There are ways to access the messages (see @kglr's answer), but generally that's an ineffective way to deal with them. You can tell Check which specific messages you care about, if that would be helpful to you. Also, just in case it wasn't clear, you can put whatever you want in place of "the result if fail". $\endgroup$
    – lericr
    Nov 20, 2023 at 0:03
  • $\begingroup$ for instance, Check[N[Pi, a], $MessageList] $\endgroup$
    – kglr
    Nov 20, 2023 at 8:59

\$Pre + EvaluationData

SetAttributes[saveMessages, HoldAll];
msgs = {};
saveMessages[input_] := (msgs = 
    Join[msgs, EvaluationData[input]@"MessagesText"]; input);

$Pre = saveMessages;

enter image description here

enter image description here

enter image description here

DownValues @ MessageList

enter image description here

Join @@ Values @ DownValues  @ MessageList

enter image description here

  • $\begingroup$ The confirmation was late. Thank you for your reply. As a result of the test, two confirmations were needed. (1) Messages generated when executing "Sin[x," are not contained in msg. (2) Using 'Check', is it possible to get msgs as the output value every time an error occurs? $\endgroup$
    – Milk
    Nov 21, 2023 at 1:39

Adapting the techique here: How to abort on any message generated?

messageHandler = Return[{##}, Internal`HandlerBlock] &;
expr = Internal`HandlerBlock[
  {"Message", messageHandler},

I'm unsure just what you would want expr to be. The message you see in the front end is the typeset output of Message. It's probably possible to capture the box form of it, but it doesn't seem that useful to me.

expr // InputForm
(*  {Hold[Message[Power::infy, HoldForm[0.^(-1)]], True]}  *)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.