I would like to start a discussion on how to best handle errors in Mathematica.
You are writing a package that many people will use. They may use your functions interactively, or they may use them inside larger functions they define. There is an error condition in your functionincorrect input, can't solve the problem, unexpected failure, etc. What should your function do?
There is already a great post by Leonid about this here:
I thought it was time to revisit the topic and share some thoughts about how each of us typically handles errors.
To get the discussion started, here are some things to think about:
- The error should be communicated in a user-friendly manner to interactive users
- There should be an easy way to catch and handle the error programmatically
- It should be easy to track down where the error occurred in a large code block (e.g. function
X
should associate its messages with X
)
Typical ways used by builtins:
- Issue a message and stay unevaluated (e.g.
Integral
) (not friendly to programmatic error handling)
- Return
$Failed
, with or without an accompanying message
- Return
Failure[...]
(e.g. Interpreter
)
Throw
something (not friendly to interactive users)
- Some functions are designed in such a way as to never error out, e.g. most
Q
functions, like OddQ
, will always return True
or False
and just return False
for input that one might consider inappropriate.
There are multiple challenges to implementing each, as well as handling each type of error.