3

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?

Milk
  • 1,688
  • 10
  • 9

3 Answers3

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.

lericr
  • 27,668
  • 1
  • 18
  • 64
  • Can't you express it with the error message above instead of "the result if fail"? – Milk Nov 19 '23 at 22:51
  • 1
    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". – lericr Nov 20 '23 at 00:03
  • for instance, Check[N[Pi, a], $MessageList] – kglr Nov 20 '23 at 08:59
3

\$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

kglr
  • 394,356
  • 18
  • 477
  • 896
  • 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? – Milk Nov 21 '23 at 01:39
2

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

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

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]}  *)
Goofy
  • 2,767
  • 10
  • 12