1. Stop (right now)
Sometimes things are just broken.
2. I saw the sign
There's no easy way around the problem. It just
doesn't work. In this case, we want to raise an error.
For example if we try to add 1 to some stuff, we get an error.
R just can't do this calculation.
The error message is also vaguely helpful - the non-numeric argument is just the
character "stuff".
3. Stop right now thank you very much
To create or raise an error, we simply use the stop() function. We can provide
some text to point the user in the direction of what went wrong.
For example, suppose we have a little function conf_int() for calculation of a confidence interval.
It's generally accepted that the standard deviation shouldn't be negative. So if this occurs, we should raise an error.
4. Catch em while you can
With the message and warning functions, we could suppress the output. This doesn't really
make sense for an error, since an error signifies that something has come wrong and probably
shouldn't be ignored.
Instead, we catch errors.
5. The try() function
The try() function acts a bit like suppress(). We can try to execute a command: if it doesn't
work, it can proceed, but crucially, we capture the error.
6. The try() idiom
When we look at the object result, we see that it's not a standard object. Instead,
it contains details about the error.
7. The try() idiom
The standard try idiom is to look at the class or type of the object. In this case,
because our command didn't work, the class of result is try-error.
This means that we adjust the flow of our code if something has gone wrong using a simple if statement.
Of course, in this case it's not clear what should be done.
8. Let's practice
OK, let's have some practice!