3 ms·
The way I frame error handling is there are three kinds of errors: The first kind of error is the "programming oops" error--division by 0, null pointer derefer
by jcranmer 6y ago
The way I frame error handling is there are three kinds of errors:
The first kind of error is the "programming oops" error--division by 0, null pointer dereference are obvious examples. These kinds of errors potentially arise from almost everywhere, but you're never expecting to handle them except at the very highest catch-all level. Consequently, you generally want to have maximum-detail error logging of the entire stack trace and perhaps the environment around the cause of the failed exception to understand what wrong.
The second case of error is the expected error class--I/O exceptions and file-not-found are the prototypical examples here. Generally, this will be handled immediately, and you may be unwilling to pay the high performance penalty of constructing the exception context if you are going to throw that context away on the very next line. Instead, your want your exception context to be no more expensive than an error code.
The third and final class of error is application errors that combine both properties. You want contextual information for errors, explaining not just what went wrong but also the sequence of processing decisions that led you to do that wrong step (e.g., pointing to configuration file entries). A stack trace isn't necessarily the worst default for context, but it's usually far from the best information. The application, when handling the error, may well want to poke heavily at the error details to display it in more user-friendly ways.
As it exists at present, most error handling systems focus on either the first or second class of errors. More rarely, they try to handle both of these classes (Rust's Result/panic divide is an example here). But there is very little support for the third class, with the closest alternative being providing context via chaining of exceptions.