Conventions
Content |
Error handling
General policy
In software intended for production use it normal for a substantial fraction of the code to be devoted to error detection and recovery. In example code this is less desirable, and taken to extremes can be a serious distraction, but code with no error handling can be criticised for setting a bad example.
The approach taken on this web site is to detect most errors, but handle them in a perfunctory manner with no attempt at cleanup or recovery. This typically means:
- throwing in exception (for languages that allow this),
- terminating the program, or
- for less serious errors, printing a warning.
Recovery is attempted for errors that are expected to occur routinely and which the software must be able to handle appropriately if it is to stand any chance of working as intended. Examples include EAGAIN
and EWOULDBLOCK
when using non-blocking sockets.
Error handling in C
Fatal errors in C are indicated by calling a function called die
, which does not return. Non-fatal errors are indicated by calling a function called warn
. Both of these take the same arguments as printf
(for the purpose of supplying an error message). They could be implemented as follows:
#include <stdarg.h> #include <stdio.h> #include <stdlib.h> void die(const char* format,...) { va_list va; va_start(va,format); vfprintf(stderr,format,va); va_end(va); exit(1); } void warn(const char* format,...) { va_list va; va_start(va,format); vfprintf(stderr,format,va); va_end(va); }
Error handling in C++
Fatal errors in C++ are indicated by throwing an instance of std::exception
. Non-fatal errors are indicated by writing a message to std::cerr
.
Error handling in Perl
Fatal errors in Perl are indicated by means of a die
statement, which normally causes an exception to be thrown. Non-fatal errors are indicated by means of a warn
statement, which normally causes a message to be written to STDOUT
.