Generally, it is better to use softer than harder error-reporting mechanisms. Calling Quit[]
seems too radical to me. What normally happens is that functions where the error occur are not in the position to make right decisions about what to do with the error, since they are likely too low-level. This is exactly the reason why exceptions exist. They (exceptions) are used to propagate the error up the execution stack to those functions which are in a position to make such decisions.
In your case, this seems to be a problem because in a simple script, two different stages are mixed together - definition-time and run-time. This is because script execution is single-pass, so it reads and executes code at the same time. What you can do to avoid this is to create functions which would compute the things you need, and store them in a separate file (package), and make your script read them in at the start. Equivalently, you can define all those functions at the start of your script. The idea is that you have just a single function to execute, so that a script can look like
f1[x_,y_,...]:=...
f2[x_,y_,z_,...]:=...
...
fn[x_]:=...
you can define those functions so that each of them throws an exception in case of some error, such as
f1[x_,y_]:=
Module[{},
some computation;
If[error, Throw[$Failed, MyException[f1,{x,y}]]]
some more computation;
result]
Then basically the main function looks like
myMainFunction[x_,y_,z_,...]:=
Catch[
Module[{a},
a = f1[x,y];
f2[x,f3[a],z];
...
],
_MyException,
handlerFunction
];
and the actual computation looks like
myMainFunction[my-starting-parameters];
Quit[]
The handlerFunction
in your main function can do different things depending on where the problem happened and what it was, but at least in this way you have a separation between the computation and the error-handling, and a much softer way to handle errors than if you call Quit[]
.
This is not specific to Mathematica. It is the same logic as in e.g. C, where you won't ordinarily put lots of exit(EXIT_FAILURE)
in your code - at least this is considered a bad style. The biggest problem with this approach is that you don't give a chance for your higher-level functions to consider the problem and perform certain finalizing or recovery actions which may be needed to gracefully exit in the case of error.