Volume 9, Issue 4
Tricks of the Trade
In and Out
Download This Issue
Staff and Contributors
In and Out
Q: I would like to abort a computation whenever an error occurs, avoiding evaluation of the subsequent expressions within a cell. For example, in the following computation, I would like to avoid computing after generates an error message.
One can immediately abort a computation by replacing the default for $Messages with a call to Abort.
However, now when an error occurs, the computation is aborted without any message.
Is there a way to display the message and then abort?
A: Omega Consulting (omegaconsultinggroup.com) answers: Using is quite a creative trick. Unfortunately, you cannot use it and also get the message. $Messages is a list of OutputStreams that any messages are written to. First, let us restore $Messages to its default value.
If the OutputStream is stdout, then you get the normal message. If it is an OutputStream to a file, then it is written to that file. You might think that the following would work:
However, it does not.
Why not? Because $Messages is evaluated before the messages are actually sent to the streams. Again, we restore $Messages to its default value.
Still there is another trick we can use, called a trap. A message is created whenever the Message function is called. We can redefine this function by unprotecting it.
Now we create a global variable, $AbortMessage, to indicate what we want to do with a Message. When the variable is True, we want to deviate from the default behavior. When False, we want the default behavior (i.e., a message).
Now we add a definition for when the variable is True. It calls Message with the variable set to False (creating a message) and then aborts.
To be safe we reprotect Message.
Now we try it.
About Mathematica | Download Mathematica Player
© 2005 Wolfram Media, Inc. All rights reserved.