Programming Search⌘K

Conceptintro

Compile-time and run-time errors

Also called compile-time error, run-time error, runtime error, static error, dynamic error, syntax error, link error.

A compile-time error is found before the program runs, such as a syntax or type error. A run-time error is found only when the bad operation runs, such as an index past the end of an array.

Applies to
core-languages

Idea

An error in a program can be found at two times. A compile-time error is found by a tool before the program runs: the compiler, the parser or a type checker. A run-time error is found only when the program runs the bad operation, and only for the input that causes it.

Python shows the two kinds in its tutorial. It calls the first kind syntax errors, "also known as parsing errors"1. For the second kind it says: "Even if a statement or expression is syntactically correct, it may cause an error when an attempt is made to execute it. Errors detected during execution are called exceptions"1.

source = "total = (1 + 2"
try:
    compile(source, "<demo>", "exec")
except SyntaxError as e:
    print(f"found before it runs: {type(e).__name__}")

values = [10, 20, 30]
for i in [1, 5]:
    try:
        print(f"values[{i}] = {values[i]}")
    except IndexError as e:
        print(f"found when it runs: {type(e).__name__}")
Output
found before it runs: SyntaxError
values[1] = 20
found when it runs: IndexError

The call to compile finds the syntax error, and no line of source runs. The index 5 is found only on the second turn of the loop, after the first turn has run.

An error that the compiler finds is cheap to fix: the programmer sees it at once, and no user sees it. An error found at run time can stay hidden until a rare input arrives. So languages and tools try to move errors from run time to compile time. The TypeScript handbook gives this as the reason for a static type-checker2.

How it works

A compiler or an interpreter reads a program in steps, and each step can find a kind of error.

  1. The parser reads the text and finds syntax errors. In JavaScript, a SyntaxError "is thrown when the JavaScript engine encounters tokens or token order that does not conform to the syntax of the language when parsing code"3.
  2. A type checker finds an operation on a value of the wrong type. Rust "is a statically typed language, which means that it must know the types of all variables at compile time"4. The TypeScript handbook says: "Ideally, we could have a tool that helps us find these bugs before our code runs. That’s what a static type-checker like TypeScript does."2
  3. The linker joins the parts of the program. In C++, "Translated translation units are combined, and all external entity references are resolved"5, so a function that is declared but has no definition is an error at this step.
  4. The program runs. Some errors depend on values that are known only now: an index past the end, a division by zero, a file that does not exist. A language that has no static types finds type errors here too: JavaScript throws a TypeError "when an operation could not be performed, typically (but not exclusively) when a value is not of the expected type"6.

Some checks are a mix of the two times. Java checks at compile time that each checked exception is caught or declared; the JLS calls this "compile-time checking for the presence of exception handlers"7. The exception itself still happens at run time.

In languages

LanguageVerdictNote
PythonNative
C++Idiom
JavaNative
CAbsent
C#Native
JavaScriptAbsent
TypeScriptAbsent
GoNative
RustNative
KotlinNativeThe Kotlin compiler finds syntax and type errors, and its type system separates nullable types from types that cannot hold null. An index past the end throws an exception at run time. No example file exists because kotlinc is not installed.
SQLIdiomA database parses and checks a statement before it runs it, so a syntax error or an unknown column is found first. A constraint violation is found when the statement runs. No example file exists.
BashAbsent
PowerShellAbsentPowerShell parses a script before it runs it, but it finds most other errors, such as a call to a command that does not exist, only at run time. No example file exists because pwsh is not installed.
HTMLDoes not applyAn HTML parser recovers from markup errors and reports no error to a program.
CSSDoes not applyA CSS parser ignores a declaration that it cannot parse and reports no error to a program.
Regular expressionsDoes not applyA regular expression engine rejects a pattern that is not valid when it compiles the pattern, but a regular expression is not a program that has run-time errors.

All ten languages find syntax errors before the code that has the error runs. They differ in how many other errors they find before the program runs, and in what they do at run time.

  • Python finds a syntax error when it parses the code, before that code runs1. It finds type errors at run time. A separate tool, mypy, "will type check your code statically: this means that it will check for errors without ever running your code"8.
  • JavaScript finds syntax errors when it parses a script, and type errors at run time as a TypeError36. TypeScript adds a static type checker2, but its types are erased from the output: "Type annotations never change the runtime behavior of your program"2.
  • Java and C# find syntax and type errors at compile time. At run time, Java throws ArrayIndexOutOfBoundsException "to indicate that an array has been accessed with an illegal index"9, and C# throws IndexOutOfRangeException for "an index that is outside its bounds"10.
  • Go finds syntax and type errors at compile time. Its spec also states that "a constant index must be in range" for an array, and that "if x is out of range at run time, a run-time panic occurs"11.
  • Rust finds syntax, type and borrowing errors at compile time. For an index past the end, the book says that [] "will cause the program to panic", and that get "returns None without panicking"12.
  • C and C++ find syntax and type errors at compile time, and the linker finds missing definitions5. They do not test an array index at run time. In C, "memory accesses outside of array bounds" are an example of undefined behavior13. In C++, std::vector::at throws std::out_of_range for a bad index14, but for operator[], "No bounds checking is performed"15.
  • Bash reads "at least one complete line of input, and all lines that make up a compound command, before executing any of the commands on that line or the compound command"16. So a syntax error at the end of a script is found only after the commands before it have run.
PythonGitHub
items = [10, 20, 30]
for i in [1, 5]:
    try:
        print(f"items[{i}] = {items[i]}")
    except IndexError as e:
        print(f"items[{i}]: run-time error ({type(e).__name__})")
Output
items[1] = 20
items[5]: run-time error (IndexError)
  • Verdict: native. Python finds a syntax error when it compiles the file, before any code runs. It finds almost all other errors at run time, such as this index past the end. A separate type checker, such as mypy, checks the types without running the code.
#include <iostream>
#include <stdexcept>
#include <vector>

int main() {
    std::vector<int> items{10, 20, 30};
    for (std::size_t i : {1, 5}) {
        try {
            int v = items.at(i);
            std::cout << "items[" << i << "] = " << v << "\n";
        } catch (const std::out_of_range&) {
            std::cout << "items[" << i << "]: run-time error (std::out_of_range)\n";
        }
    }
}
Output
items[1] = 20
items[5]: run-time error (std::out_of_range)
  • Verdict: idiom. The C++ compiler finds syntax and type errors, and the linker finds a function that has no definition. at tests the index and throws std::out_of_range. The operator [] does not test it: an index past the end has undefined behavior.
JavaGitHub
public class Main {
    public static void main(String[] args) {
        int[] items = {10, 20, 30};
        for (int i : new int[] {1, 5}) {
            try {
                System.out.println("items[" + i + "] = " + items[i]);
            } catch (ArrayIndexOutOfBoundsException e) {
                System.out.println("items[" + i + "]: run-time error (" + e.getClass().getSimpleName() + ")");
            }
        }
    }
}
Output
items[1] = 20
items[5]: run-time error (ArrayIndexOutOfBoundsException)
  • Verdict: native. The Java compiler finds syntax and type errors, and checks that each checked exception is caught or declared. The run-time system tests each array index, and throws an exception for an index that is not valid.
#include <stdio.h>

int main(void) {
    int items[] = {10, 20, 30};
    size_t n = sizeof items / sizeof items[0];
    size_t indexes[] = {1, 5};
    for (int k = 0; k < 2; k++) {
        size_t i = indexes[k];
        if (i < n) {
            printf("items[%zu] = %d\n", i, items[i]);
        } else {
            printf("items[%zu]: out of range (tested by the code)\n", i);
        }
    }
    return 0;
}
Output
items[1] = 20
items[5]: out of range (tested by the code)
  • Verdict: absent. The C compiler finds syntax and type errors, and the linker finds a function that has no definition. Nothing tests an array index at run time: an index past the end has undefined behavior, so the code must test it.
using System;

int[] items = { 10, 20, 30 };
foreach (int i in new[] { 1, 5 })
{
    try
    {
        Console.WriteLine($"items[{i}] = {items[i]}");
    }
    catch (IndexOutOfRangeException e)
    {
        Console.WriteLine($"items[{i}]: run-time error ({e.GetType().Name})");
    }
}
Output
items[1] = 20
items[5]: run-time error (IndexOutOfRangeException)
  • Verdict: native. The C# compiler finds syntax and type errors. The run-time system tests each array index and throws IndexOutOfRangeException.
JavaScriptGitHub
const items = [10, 20, 30];
for (const i of [1, 5]) {
  console.log(`items[${i}] = ${items[i]}`);
}
Output
items[1] = 20
items[5] = undefined
  • Verdict: absent. JavaScript finds a syntax error when it parses the script, and throws a TypeError at run time for an operation on a value of the wrong type. An index past the end is not an error: the result is undefined, and the program goes on.
TypeScriptGitHub
const items: number[] = [10, 20, 30];
for (const i of [1, 5]) {
  console.log(`items[${i}] = ${items[i]}`);
}
Output
items[1] = 20
items[5] = undefined
  • Verdict: absent. The TypeScript compiler finds type errors before the program runs, but here the type of items[i] is number, so the compiler does not report the index past the end. The run-time result is undefined, as in JavaScript.
package main

import "fmt"

func get(items []int, i int) (v int, err error) {
	defer func() {
		if r := recover(); r != nil {
			err = fmt.Errorf("%v", r)
		}
	}()
	return items[i], nil
}

func main() {
	items := []int{10, 20, 30}
	for _, i := range []int{1, 5} {
		v, err := get(items, i)
		if err != nil {
			fmt.Printf("items[%d]: %v\n", i, err)
			continue
		}
		fmt.Printf("items[%d] = %d\n", i, v)
	}
}
Output
items[1] = 20
items[5]: runtime error: index out of range [5] with length 3
  • Verdict: native. The Go compiler finds syntax and type errors, and the spec makes an import that the package does not use illegal. The compiler rejects a constant index that is out of range for an array. A variable index is tested at run time, and a bad one causes a run-time panic, which recover turns into an error here.
RustGitHub
fn main() {
    let items = vec![10, 20, 30];
    for i in [1, 5] {
        match items.get(i) {
            Some(v) => println!("items[{i}] = {v}"),
            None => println!("items[{i}]: no item (get returned None)"),
        }
    }
}
Output
items[1] = 20
items[5]: no item (get returned None)
  • Verdict: native. The Rust compiler finds syntax and type errors, and the borrow checker finds a reference that breaks the borrowing rules. An index past the end is found at run time: items[i] panics, and items.get(i) returns None, so the type makes the caller handle the missing item.
BashGitHub
items=(10 20 30)
for i in 1 5; do
  echo "items[$i] = '${items[$i]}'"
done
Output
items[1] = '20'
items[5] = ''
  • Verdict: absent. Bash reads a line, or a full compound command, before it runs it, so a syntax error later in the script is found only when Bash reaches it. An index past the end of an array is not an error: the result is an empty string.
  • Static and dynamic typing. A statically typed language finds type errors at compile time, and a dynamically typed language finds them at run time. See static-and-dynamic-typing.
  • Stricter options. A checker can find more errors when an option tells it to. For example, the TypeScript option noUncheckedIndexedAccess "will add undefined to any un-declared field in the type"17, so the code must test for a missing value.
  • Types that make a run-time check visible. Rust's get returns an Option, so the compiler makes the caller handle the missing item12. The run-time check stays, but the compiler checks that the code handles its result.
  • Undefined behavior. C and C++ do not report some run-time errors at all. The result is undefined behavior, not an error13. See undefined-behavior.

Pitfalls

A run-time error that the tests do not reach

A run-time error happens only on the path and the input that cause it. A test that does not use that input does not find it.

This code runs but gives a wrong answer on purpose.

def label(count):
    if count == 1:
        return "1 item"
    return str(count) + " items"

def report(count):
    if count < 0:
        return "bad count: " + count
    return label(count)

print(report(3))
Output
3 items

The program runs and prints the correct result. But the line for a negative count adds a string and an integer, and Python finds this only when count is negative: it raises a TypeError at run time. A static type checker such as mypy reports this line without running the code8.

An unchecked index in C

C does not test an index at run time, so an index past the end is not reported as an error13. The program can print a wrong value, or crash, or seem to work.

For example, the loop for (int i = 0; i <= 3; i++) over an array of three items reads items[3], which is past the end. The behavior of the program is undefined13. "Compilers are not required to diagnose undefined behavior"13, and the program does not have to fail.

A late syntax error in Bash

Because Bash reads and runs one line or compound command at a time16, the commands before a syntax error run.

This code runs but gives a wrong answer on purpose.

script='echo "step 1 done"
echo "step 2 done"
if [ 1 -eq 1 ]; then echo "step 3"'
bash -c "$script" 2>/dev/null
echo "status $?"
Output
step 1 done
step 2 done
status 2

Steps 1 and 2 run before Bash finds that the if has no fi. A script that changes files can stop halfway. The option -n tells Bash to "Read commands but do not execute them", and the manual says that this "may be used to check a script for syntax errors"16.

Cost

A compile-time check costs time when the program is built, and nothing when it runs. Milner wrote that once the type checker has accepted a program, "code may be generated which assumes that no objects carry their types at run-time. This is widely accepted as yielding efficient object code"18.

A run-time check costs a test each time the operation runs. C++ gives the choice: at tests the index14, and operator[] does not15.

The other cost is when a person finds the error. A compile-time error is found by the programmer. A run-time error can be found by a user, after the program has shipped.

History

In 1978, Robin Milner published a paper on type polymorphism in programming. The paper gives "a compile time type-checking algorithm" and a theorem that "well-type programs cannot “go wrong”"18. The type checker was part of the language ML, and Milner wrote that it "has proved to be a valuable filter which traps a significant proportion of programming errors"18.

References

  1. Errors and Exceptions, The Python Tutorial, 8.1 Syntax Errors; 8.2 Exceptions
  2. The Basics, TypeScript Handbook, Static type-checking
  3. SyntaxError, MDN Web Docs, Description
  4. Data Types, The Rust Programming Language, Chapter 3.2
  5. Phases of translation, cppreference.com, Phase 9 Linking
  6. TypeError, MDN Web Docs, Description
  7. Chapter 11. Exceptions, The Java Language Specification, Java SE 25 Edition, 11.2 Compile-Time Checking of Exceptions
  8. Getting started, mypy documentation, Installing and running mypy
  9. ArrayIndexOutOfBoundsException, Java SE 21 API, Class description
  10. IndexOutOfRangeException Class, .NET API, Definition
  11. The Go Programming Language Specification, Index expressions; Import declarations
  12. Storing Lists of Values with Vectors, The Rust Programming Language, Reading Elements of Vectors
  13. Undefined behavior, cppreference.com (C), Description; Access out of bounds
  14. std::vector::at, cppreference.com, Description; Exceptions
  15. std::vector::operator[], cppreference.com, Description; Notes
  16. Bash Reference Manual, 6.6 Aliases; 4.3.1 The Set Builtin (-n)
  17. noUncheckedIndexedAccess, TSConfig Reference, Description
  18. A theory of type polymorphism in programming (Milner, Journal of Computer and System Sciences 17, 1978), Abstract; Section 1 Introduction

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.

LadderLevelWhat the next level needs
Human proofH0 no proof
  • add a proof in proofs/ (06.5)
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW4 complete
  • a review of the text: no review record reviews/ZAHKXJ/text.yaml