Conceptcore
Error codes
Also called error code, return code, status code, errno, HRESULT, exit code.
An error code is a number that a function returns, or stores in a known place, to tell the caller which error happened. The caller must test it after each call.
- Applies to
- core-languages
Idea
An error code is a number that tells the caller which error happened. The function returns it, or stores it in a known place, and the caller tests it after the call. A code of zero often means success, and each other value names one error.
C uses error codes in its standard library. Several functions "indicate errors by writing positive integers to errno"1, and the man page says that the value "is significant only when the return value of the call indicated an error"2. So the caller tests the return value first, and reads errno only after a failure.
#include <errno.h>
#include <stdio.h>
#include <string.h>
int main(void) {
FILE *f = fopen("/no/such/file", "r");
if (f == NULL) {
int code = errno;
printf("fopen failed: errno = %d (%s)\n", code, strerror(code));
return 0;
}
fclose(f);
return 0;
}
fopen failed: errno = 2 (No such file or directory)
fopen returns NULL, the program copies errno at once, and strerror turns the number into a message2. The number 2 is the code for ENOENT on Linux, but "The error numbers that correspond to each symbolic name vary across UNIX systems"2, so a program tests the name, not the number.
How it works
A design with error codes has three parts.
- A set of codes. Each code is a named constant. C names its codes with macros that begin with the letter
E1, and Python's moduleerrnomaps each number to its name, so thaterrno.errorcode[errno.EPERM]"maps to 'EPERM'"3. - A channel for the code. The function returns the code, or it returns a special value and puts the code in a variable. The Seventh Edition Unix manual describes the second form: "An error condition is indicated by an otherwise impossible returned value. Almost always this is -1"4, and the error number is in
errno. - A test at the caller. The caller tests the code after each call and decides what to do. A code says nothing until a person or a program reads it.
Some codes carry more than one fact. A Windows HRESULT is 32 bits: "The high-order bit in the HRESULT or SCODE indicates whether the return value represents success or failure"5, and other fields hold a facility, which names the part of the system, and the code itself6.
A shell uses the same idea for whole programs. In Bash, command1 && command2 runs the second command "if, and only if, command1 returns an exit status of zero (success)"7. A status that is not zero is an error code.
In languages
| Language | Verdict | Note |
|---|---|---|
| Python | Idiom | |
| C++ | Standard library | |
| Java | Idiom | |
| C | Native | |
| C# | Idiom | |
| JavaScript | Idiom | |
| TypeScript | Idiom | |
| Go | Idiom | |
| Rust | Idiom | |
| Kotlin | Idiom | Kotlin reports errors with exceptions, so a function that returns a code is a choice of the programmer. No example file exists because kotlinc is not installed. |
| SQL | Native | The SQL standard defines SQLSTATE, a code of five characters that reports the result of each statement. No example file exists. |
| Bash | Native | |
| PowerShell | Native | PowerShell sets $LASTEXITCODE to the exit code of the last native program that ran, and $? to whether the last command succeeded. No example file exists because pwsh is not installed. |
| HTML | Does not apply | HTML has no error mechanism for a program. HTTP status codes belong to the protocol, not to HTML. |
| CSS | Does not apply | CSS has no error mechanism for a program. |
| Regular expressions | Does not apply | A regular expression has no error mechanism of its own. |
- C has no exceptions, so return codes and
errnoare its usual mechanism1. The C++ Core Guidelines advise against theerrnostyle: "Global state is hard to manage and it is easy to forget to check it."8 - C++ usually throws exceptions, but some functions return a code.
std::from_chars"Throws nothing" and reports a failure in its result, withecequal tostd::errc::result_out_of_rangewhen the number is too large9. The attributenodiscardasks the compiler for a warning when a caller ignores a result: "the compiler is encouraged to issue a warning"10. - Bash uses the exit status of each command and function as its error code7.
- Java, C#, Python and JavaScript report errors with exceptions. Codes still appear inside them: an exception in .NET has an
HResult, "a coded numerical value that is assigned to a specific exception"6, and a Node.js error haserror.code, "a string label that identifies the kind of error"11. - Go and Rust return errors as values, not as bare integers. They keep the operating system code inside the value. In Go, "An Errno is an unsigned number describing an error condition. It implements the error interface."12 In Rust,
raw_os_error"Returns the OS error that this error represents (if any)"13.
OK, EMPTY, NOT_A_NUMBER, OUT_OF_RANGE = 0, 1, 2, 3
NAMES = ["ok", "empty", "not a number", "out of range"]
def parse_port(text):
"""Return (code, port). The port is valid only when the code is OK."""
if text == "":
return EMPTY, 0
if not (text.isascii() and text.isdigit()):
return NOT_A_NUMBER, 0
port = int(text)
if port > 65535:
return OUT_OF_RANGE, 0
return OK, port
for text in ["8080", "", "x", "99999"]:
code, port = parse_port(text)
if code != OK:
print(f"'{text}' -> error code {code} ({NAMES[code]})")
else:
print(f"'{text}' -> port {port}")
'8080' -> port 8080
'' -> error code 1 (empty)
'x' -> error code 2 (not a number)
'99999' -> error code 3 (out of range)
- Verdict: idiom. Python reports errors with exceptions, so a function that returns a code is a choice of the programmer. The operating system codes are still visible: an
OSErrorhas the attributeerrno, and the moduleerrnomaps each code to a name such asENOENT.
#include <charconv>
#include <iostream>
#include <string>
#include <system_error>
enum Code { Ok, Empty, NotANumber, OutOfRange };
const char* names[] = {"ok", "empty", "not a number", "out of range"};
// Returns a code. On success, writes the port.
Code parse_port(const std::string& text, int& port) {
if (text.empty()) return Empty;
int value = 0;
const char* last = text.data() + text.size();
auto [end, ec] = std::from_chars(text.data(), last, value);
if (ec == std::errc::invalid_argument || end != last) return NotANumber;
if (ec == std::errc::result_out_of_range || value < 0 || value > 65535) return OutOfRange;
port = value;
return Ok;
}
int main() {
for (std::string text : {"8080", "", "x", "99999"}) {
int port = 0;
Code code = parse_port(text, port);
if (code != Ok) {
std::cout << "'" << text << "' -> error code " << code << " (" << names[code] << ")\n";
} else {
std::cout << "'" << text << "' -> port " << port << "\n";
}
}
}
'8080' -> port 8080
'' -> error code 1 (empty)
'x' -> error code 2 (not a number)
'99999' -> error code 3 (out of range)
- Verdict: stdlib. C++ usually throws exceptions, but some standard functions return a code.
std::from_charsthrows nothing; it reports a failure in theecfield of its result, asstd::errc::invalid_argumentorstd::errc::result_out_of_range.
public class Main {
static final int OK = 0, EMPTY = 1, NOT_A_NUMBER = 2, OUT_OF_RANGE = 3;
static final String[] NAMES = {"ok", "empty", "not a number", "out of range"};
// Returns a code. On success, writes the port to out[0].
static int parsePort(String text, int[] out) {
if (text.isEmpty()) return EMPTY;
if (!text.matches("[0-9]+")) return NOT_A_NUMBER;
if (text.length() > 5 || Integer.parseInt(text) > 65535) return OUT_OF_RANGE;
out[0] = Integer.parseInt(text);
return OK;
}
public static void main(String[] args) {
for (String text : new String[] {"8080", "", "x", "99999"}) {
int[] port = new int[1];
int code = parsePort(text, port);
if (code != OK) {
System.out.println("'" + text + "' -> error code " + code + " (" + NAMES[code] + ")");
} else {
System.out.println("'" + text + "' -> port " + port[0]);
}
}
}
}
'8080' -> port 8080
'' -> error code 1 (empty)
'x' -> error code 2 (not a number)
'99999' -> error code 3 (out of range)
- Verdict: idiom. Java reports errors with exceptions, and its tutorial names the separation of error-handling code from regular code as the first advantage of exceptions. A method has one return value, so this one writes the port to an array of one element.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
enum { OK, EMPTY, NOT_A_NUMBER, OUT_OF_RANGE };
static const char *names[] = {"ok", "empty", "not a number", "out of range"};
/* Returns a code. On success, writes the port to *port. */
static int parse_port(const char *text, int *port) {
size_t n = strlen(text);
if (n == 0) return EMPTY;
if (strspn(text, "0123456789") != n) return NOT_A_NUMBER;
if (n > 5 || atoi(text) > 65535) return OUT_OF_RANGE;
*port = atoi(text);
return OK;
}
int main(void) {
const char *texts[] = {"8080", "", "x", "99999"};
for (int i = 0; i < 4; i++) {
int port = 0;
int code = parse_port(texts[i], &port);
if (code != OK) {
printf("'%s' -> error code %d (%s)\n", texts[i], code, names[code]);
} else {
printf("'%s' -> port %d\n", texts[i], port);
}
}
return 0;
}
'8080' -> port 8080
'' -> error code 1 (empty)
'x' -> error code 2 (not a number)
'99999' -> error code 3 (out of range)
- Verdict: native. C has no exceptions, so error codes are the usual mechanism. Several standard library functions "indicate errors by writing positive integers to errno", and many functions return a code, as
parse_portdoes here.
using System;
static class Program
{
const int Ok = 0, Empty = 1, NotANumber = 2, OutOfRange = 3;
static readonly string[] Names = { "ok", "empty", "not a number", "out of range" };
// Returns a code. On success, sets port.
static int ParsePort(string text, out int port)
{
port = 0;
if (text.Length == 0) return Empty;
foreach (char c in text)
{
if (c < '0' || c > '9') return NotANumber;
}
if (text.Length > 5 || int.Parse(text) > 65535) return OutOfRange;
port = int.Parse(text);
return Ok;
}
static void Main()
{
foreach (string text in new[] { "8080", "", "x", "99999" })
{
int code = ParsePort(text, out int port);
if (code != Ok)
{
Console.WriteLine($"'{text}' -> error code {code} ({Names[code]})");
}
else
{
Console.WriteLine($"'{text}' -> port {port}");
}
}
}
}
'8080' -> port 8080
'' -> error code 1 (empty)
'x' -> error code 2 (not a number)
'99999' -> error code 3 (out of range)
- Verdict: idiom. C# reports errors with exceptions, but each exception has an
HResultproperty, "a coded numerical value that is assigned to a specific exception". Anoutparameter gives the method a second result.
const OK = 0, EMPTY = 1, NOT_A_NUMBER = 2, OUT_OF_RANGE = 3;
const NAMES = ["ok", "empty", "not a number", "out of range"];
// Returns [code, port]. The port is valid only when the code is OK.
function parsePort(text) {
if (text === "") return [EMPTY, 0];
if (!/^[0-9]+$/.test(text)) return [NOT_A_NUMBER, 0];
const port = Number(text);
if (port > 65535) return [OUT_OF_RANGE, 0];
return [OK, port];
}
for (const text of ["8080", "", "x", "99999"]) {
const [code, port] = parsePort(text);
if (code !== OK) {
console.log(`'${text}' -> error code ${code} (${NAMES[code]})`);
} else {
console.log(`'${text}' -> port ${port}`);
}
}
'8080' -> port 8080
'' -> error code 1 (empty)
'x' -> error code 2 (not a number)
'99999' -> error code 3 (out of range)
- Verdict: idiom. JavaScript reports errors with exceptions. Node.js adds a code to many of its errors:
error.codeis "a string label that identifies the kind of error", such asENOENTfor a file that does not exist.
const OK = 0, EMPTY = 1, NOT_A_NUMBER = 2, OUT_OF_RANGE = 3;
const NAMES = ["ok", "empty", "not a number", "out of range"];
// Returns [code, port]. The port is valid only when the code is OK.
function parsePort(text: string): [number, number] {
if (text === "") return [EMPTY, 0];
if (!/^[0-9]+$/.test(text)) return [NOT_A_NUMBER, 0];
const port = Number(text);
if (port > 65535) return [OUT_OF_RANGE, 0];
return [OK, port];
}
for (const text of ["8080", "", "x", "99999"]) {
const [code, port] = parsePort(text);
if (code !== OK) {
console.log(`'${text}' -> error code ${code} (${NAMES[code]})`);
} else {
console.log(`'${text}' -> port ${port}`);
}
}
'8080' -> port 8080
'' -> error code 1 (empty)
'x' -> error code 2 (not a number)
'99999' -> error code 3 (out of range)
- Verdict: idiom. As in JavaScript, a function that returns a code is a choice of the programmer. The tuple type
[number, number]documents the two results, but the compiler does not make the caller test the code.
package main
import (
"errors"
"fmt"
"strconv"
)
const (
OK = iota
Empty
NotANumber
OutOfRange
)
var names = []string{"ok", "empty", "not a number", "out of range"}
// parsePort returns a port and a code. The port is valid only when the code is OK.
func parsePort(text string) (int, int) {
if text == "" {
return 0, Empty
}
port, err := strconv.Atoi(text)
if errors.Is(err, strconv.ErrRange) {
return 0, OutOfRange
}
if err != nil {
return 0, NotANumber
}
if port < 0 || port > 65535 {
return 0, OutOfRange
}
return port, OK
}
func main() {
for _, text := range []string{"8080", "", "x", "99999"} {
port, code := parsePort(text)
if code != OK {
fmt.Printf("'%s' -> error code %d (%s)\n", text, code, names[code])
} else {
fmt.Printf("'%s' -> port %d\n", text, port)
}
}
}
'8080' -> port 8080
'' -> error code 1 (empty)
'x' -> error code 2 (not a number)
'99999' -> error code 3 (out of range)
- Verdict: idiom. Go returns errors as values of the
errorinterface, not as integers. An operating system code is still a number: "An Errno is an unsigned number describing an error condition. It implements the error interface."
#[derive(Clone, Copy, PartialEq)]
enum Code {
Ok = 0,
Empty = 1,
NotANumber = 2,
OutOfRange = 3,
}
const NAMES: [&str; 4] = ["ok", "empty", "not a number", "out of range"];
// Returns a code. On success, writes the port.
fn parse_port(text: &str, port: &mut u16) -> Code {
if text.is_empty() {
return Code::Empty;
}
if !text.bytes().all(|b| b.is_ascii_digit()) {
return Code::NotANumber;
}
match text.parse::<u16>() {
Ok(p) => {
*port = p;
Code::Ok
}
Err(_) => Code::OutOfRange,
}
}
fn main() {
for text in ["8080", "", "x", "99999"] {
let mut port = 0;
let code = parse_port(text, &mut port);
if code != Code::Ok {
println!("'{text}' -> error code {} ({})", code as i32, NAMES[code as usize]);
} else {
println!("'{text}' -> port {port}");
}
}
}
'8080' -> port 8080
'' -> error code 1 (empty)
'x' -> error code 2 (not a number)
'99999' -> error code 3 (out of range)
- Verdict: idiom. Rust returns errors in a
Result, so a function that returns a code is unusual. Anstd::io::Errorkeeps the operating system code:raw_os_error"Returns the OS error that this error represents (if any)".
names=("ok" "empty" "not a number" "out of range")
# Prints the port. The exit status is the code.
parse_port() {
local text=$1
[ -z "$text" ] && return 1
case $text in
*[!0-9]*) return 2 ;;
esac
[ "${#text}" -gt 5 ] && return 3
[ "$text" -gt 65535 ] && return 3
echo "$text"
return 0
}
for text in "8080" "" "x" "99999"; do
port=$(parse_port "$text")
code=$?
if [ "$code" -ne 0 ]; then
echo "'$text' -> error code $code (${names[$code]})"
else
echo "'$text' -> port $port"
fi
done
'8080' -> port 8080
'' -> error code 1 (empty)
'x' -> error code 2 (not a number)
'99999' -> error code 3 (out of range)
- Verdict: native. Each command and function in Bash returns an exit status, and a status that is not zero is an error code. A function sets it with
return, and the caller reads it in$?.
Variations and related ideas
- Codes and exceptions. The Java tutorial shows a file reader written with error codes, and lists as the first advantage of exceptions "Separating Error-Handling Code from "Regular" Code"14. With codes, each function between the error and the handler must also return the code up the call stack14. See exception-handling.
- Codes inside error values. A Go
erroror a RustResultcan hold a code and also a message and a cause1312. See errors-as-values. - Status codes of a process. A program returns an exit status to the shell that ran it, and the shell tests it with
&&,||andif7. - Codes in an exception. A .NET exception and a Node.js error carry a code, so a handler can test the code instead of the message611. Node.js says that
error.code"is the most stable way to identify an error"11.
Pitfalls
Testing the code the wrong way round
A function that returns 0 for success makes the test look inverted. In C, if (f()) is true when f fails.
This code runs but gives a wrong answer on purpose.
#include <stdio.h>
#include <string.h>
/* Returns 0 for success and 1 for an error. */
static int parse_digit(const char *text, int *out) {
if (strlen(text) != 1 || text[0] < '0' || text[0] > '9') return 1;
*out = text[0] - '0';
return 0;
}
int main(void) {
int value = -1;
if (parse_digit("x", &value)) {
printf("parsed %d\n", value);
}
return 0;
}
parsed -1
The test reads like "if the parse worked", but it is true for the error code 1. The program then uses a value that parse_digit never set. Write the test as if (parse_digit("x", &value) != 0) for the error case.
A stale errno
errno keeps its old value after a call that succeeds. The man page says that "a function that succeeds is allowed to change errno" and that "The value of errno is never set to zero by any system call or library function"2.
This code runs but gives a wrong answer on purpose.
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
int main(void) {
FILE *f = fopen("/no/such/file", "r");
if (f != NULL) fclose(f);
long n = strtol("42", NULL, 10);
if (errno != 0) {
printf("strtol failed? errno = %d, n = %ld\n", errno, n);
}
return 0;
}
strtol failed? errno = 2, n = 42
strtol worked, but errno still holds the code from fopen. The man page gives the fix for functions where the return value cannot show an error: set errno to zero before the call, and test it after2.
A lost exit status in a pipeline
In Bash, "The exit status of a pipeline is the exit status of the last command in the pipeline, unless the pipefail option is enabled"7. So an error in the first command is lost.
This code runs but gives a wrong answer on purpose.
grep "x" /no/such/file 2>/dev/null | sort
echo "status $?"
status 0
grep fails, but sort succeeds, so the status is 0. With set -o pipefail, the status is that of "the last (rightmost) command to exit with a non-zero status"7, here the status of grep.
Cost
Returning a code needs no allocation and no exception. For example, std::from_chars is "locale-independent, non-allocating, and non-throwing"9.
The cost is in the code that calls it. The Java tutorial's file reader with error codes needs a nested if for each step14, and each caller up the stack must test and return the code again14. The Core Guidelines add that "it is easy to forget to check it"8.
History
The Seventh Edition Unix manual describes the convention that C still uses. A system call returns an impossible value, "Almost always this is -1", and "An error number is also made available in the external variable errno"4. It also warns that "Errno is not cleared on successful calls, so it should be tested only after an error has occurred"4.
The first ISO C standard, ISO/IEC 9899:1990, defined errno in section 4.1.3, "Errors <errno.h>"1. Each later C standard keeps it1.
References
- errno, cppreference.com (C), Description; References
- errno(3), Linux manual page, DESCRIPTION
- errno, Python Standard Library, errno.errorcode
- intro(2), Unix Seventh Edition manual, DESCRIPTION
- Structure of COM Error Codes, Win32 documentation, Whole page
- Exception.HResult Property, .NET API, Definition; Remarks
- Bash Reference Manual, 3.2.3 Pipelines; 3.2.4 Lists of Commands; 3.7.5 Exit Status
- C++ Core Guidelines, E.28
- std::from_chars, cppreference.com, Return value; Exceptions
- C++ attribute nodiscard, cppreference.com, Explanation
- Errors, Node.js documentation, error.code
- Package syscall, Go standard library, type Errno
- std::io::Error, Rust standard library, last_os_error; raw_os_error
- Advantages of Exceptions, The Java Tutorials, Advantage 1; Advantage 2
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H0 no proof |
|
| Lean | L0 no Lean part |
|
| Visual | V0 none |
|
| Writing | W4 complete |
|
Tag A63VKT Edit this page History Report an error Markdown