Programming Search⌘K

Conceptadvanced

Bottom type

Also called never type, empty type, uninhabited type, zero type, Never, NoReturn, never, Nothing, !, Void, ⊥.

The bottom type has no values and is a subtype of every type. It is the result type of code that never returns, such as a throw, a panic or an endless loop.

Applies to
core-languages

Idea

Some expressions never give a value. A raise, a call to exit and an endless loop all stop the normal flow, so the code after them does not run. The bottom type is the type of such an expression. It has no values, so a function whose result type is the bottom type can never return normally. Because no value of it can exist, the bottom type fits where any other type is expected, which lets a branch that fails sit next to a branch that gives a value. Python calls it Never, Rust writes !, Kotlin has Nothing, and TypeScript has never.

from typing import Never, NoReturn, assert_never


def fail(msg: str) -> Never:
    raise ValueError(msg)


def parse_age(s: str) -> int:
    # Each branch must give an int. fail gives no value, so it fits here.
    return int(s) if s.isdigit() else fail(f"bad age: {s!r}")


print(parse_age("42"))
try:
    parse_age("x")
except ValueError as e:
    print("error:", e)


def describe(x: int | str) -> str:
    if isinstance(x, int):
        return "int"
    elif isinstance(x, str):
        return "str"
    else:
        # A type checker narrows x to Never here, so this line is unreachable.
        assert_never(x)


print(describe(1), describe("a"))
try:
    describe(1.5)  # type: ignore[arg-type]
except AssertionError as e:
    print(type(e).__name__)
print(Never, NoReturn)
Output
42
error: bad age: 'x'
int str
AssertionError
typing.Never typing.NoReturn

fail has the result type Never, so a type checker accepts it in the else branch of an expression whose type is int. In describe, the first two branches cover every value of int | str, so a type checker gives x the type Never in the last branch, and assert_never confirms that this branch is unreachable. Python does not check annotations when the program runs, so the call with 1.5 reaches assert_never, which raises an AssertionError.

How it works

A subtype of all types. "In type theory, a theory within mathematical logic, the bottom type of a type system is the type that is a subtype of all other types"1. "Where such a type exists, it is often represented with the up tack (⊥) symbol"1. It is the dual of the top type, the type that every value has.

No values. "When the bottom type is uninhabited, a function whose return type is bottom cannot return any value, not even the lone value of a unit type"1. That is the difference from the unit type: a function that returns unit returns normally with a value that carries no information, and a function that returns bottom does not return at all. In Rust, "The never type ! is a type with no values, representing computations that never complete, also known as diverging computations"2.

Why it fits anywhere. A value of the bottom type can never exist, so a rule that lets such a value become any other type can never go wrong at run time. The Rust reference says, "Expressions of type ! can be coerced into any type"2, and the standard library explains, "This is sound because a value of type ! can never exist, and any coercion of such a value will never actually execute"3. This is how a match arm or an if branch can end in return, panic! or continue while the other arms give values. In Rust, "return, break, continue, become, and infinite loop expressions all have type !, as the code following them is unreachable"3.

Exhaustiveness and unreachable code. After a program has tested a value against every case of a union, no case is left, and the type of the value in the remaining branch is the bottom type. In Python, "For a call to assert_never to pass type checking, the inferred type of the argument passed in must be the bottom type, Never, and nothing else"4. A type checker reports an error if a case is missing, so the bottom type turns a missing case into a compile-time error. The TypeScript handbook says the same of never: "you can use narrowing and rely on never turning up to do exhaustive checking in a switch statement"5. See exhaustive matching.

A type with no values as a parameter. A generic type with the bottom type as its argument can rule out a case. In Rust, "the Err variant of a Result<T, !> cannot be constructed either"3, so Result<T, !> is the result of an operation that cannot fail. A function that takes the bottom type as a parameter cannot be called: Python documents Never as the parameter type of "a function that should never be called, as there are no valid arguments"4.

The names in each language. In Python, "Never and NoReturn represent the bottom type, a type that has no members"4. Kotlin says that "Nothing has no instances" and that "if a function has the return type of Nothing, it means that it never returns (always throws an exception)"6. Haskell has Void in Data.Void, "A logically uninhabited data type, used to indicate that a given term should not exist"7. In TypeScript, "The never type represents the type of values that never occur"8, and "never is a subtype of and assignable to every type"8.

In languages

LanguageVerdictNote
PythonStandard library
C++Idiom
JavaAbsent
CIdiom
C#Idiom
JavaScriptAbsent
TypeScriptNativeNever is the bottom type. TypeScript infers it for a function whose end cannot be reached and for a value after narrowing has removed every case of a union, and an assignment to never checks that a switch is exhaustive. No example file exists.
GoIdiom
RustNative
KotlinNativeNothing has no instances, and a function that always throws has the result type Nothing. No example file exists because kotlinc is not installed.
SQLDoes not applySQL has no result type for code that does not return. A failed statement raises an error, which the database reports.
BashDoes not applyBash has no static types, so it has no type for code that does not return. The exit builtin ends the script.
PowerShellAbsentPowerShell has no bottom type. The throw keyword and the exit keyword stop the normal flow, but no type describes them. No example file exists because pwsh is not installed.
HTMLDoes not applyHTML has no types of values.
CSSDoes not applyCSS has no types of values in this sense.
Regular expressionsDoes not applyA regular expression has no values and no types.
Language Verdict Mechanism
Python stdlib typing.Never and typing.NoReturn, checked by a type checker, not at run time
JavaScript absent no static types; throw is a statement, so a helper function that throws stands in
TypeScript native never, inferred for a function that cannot reach its end and for a union with no cases left
Java absent no bottom type; a method that always throws declares some result type; the null type is not a bottom type
Kotlin native Nothing, which has no instances; a function that always throws has the result type Nothing
C# idiom no bottom type; throw expressions fit where a value is expected; [DoesNotReturn] for analysis
Go idiom no bottom type; a call to panic is a terminating statement, so no return must follow it
Rust native !, the type of panic!, return, break, continue and loop; Infallible for errors that cannot occur
C idiom no bottom type; _Noreturn or noreturn marks a function that does not return, such as exit
C++ idiom no bottom type; noreturn on a function; a throw expression in a conditional expression
Bash n/a Bash has no static types; exit ends the script
PowerShell absent no bottom type; throw and exit stop the normal flow
SQL n/a SQL has no result type for code that does not return
Regex n/a a pattern has no values
HTML n/a HTML has no types of values
CSS n/a CSS has no types of values in this sense

Rust, Kotlin and TypeScript have a bottom type in the language, and the compiler uses it to type return, throw and loops. Python has one in its type annotations, for type checkers. In C, C++, C# and Go, only an attribute or a rule about statements says that a call does not return, and no expression has a bottom type. In C#, "You can also use throw as an expression"9, so name ?? throw ... fits where a string is expected, and the attribute DoesNotReturn "Specifies that a method will never return under any circumstance"10. Java has a null type, which is a subtype of every reference type, but "the null type is not a bottom type as described above, it is not a subtype of int and other primitive types"1. Also, "Because the null type has no name, it is impossible to declare a variable of the null type"11.

The example files show these differences. Python shows Never on a function that calls sys.exit and shows that Python does not check the annotation. JavaScript uses a helper function that throws, because throw is a statement. Java uses a generic method that throws to fill a branch of a conditional expression and a switch arm. C# uses throw expressions with ?? and the conditional operator. Go shows a function that ends in panic without return. Rust shows a function that returns !, continue and return in a match, and Infallible. C and C++ show noreturn functions.

PythonGitHub
import sys
from typing import Never, get_type_hints


def stop(code: int) -> Never:
    sys.exit(code)


# sys.exit raises SystemExit, so the call never returns normally.
try:
    stop(3)
except SystemExit as e:
    print("exit code", e.code)


def bad() -> Never:
    return None  # a type checker reports this line, but Python runs it


print(bad(), get_type_hints(stop)["return"])
Output
exit code 3
None typing.Never
  • Verdict: stdlib. typing.Never and typing.NoReturn are the bottom type for type checkers. stop calls sys.exit, which raises SystemExit, so the call never gives a value. Python does not check the annotation when the program runs, so bad returns None even though its result type is Never, and only a type checker reports the error.
#include <iostream>
#include <stdexcept>
#include <string>

[[noreturn]] void fail(const std::string& msg) {
    throw std::invalid_argument(msg);
}

int port(const std::string& s) {
    // A throw expression may be one operand of the conditional operator.
    return !s.empty() && s.find_first_not_of("0123456789") == std::string::npos
               ? std::stoi(s)
               : throw std::invalid_argument("bad port: " + s);
}

int checked_div(int a, int b) {
    if (b == 0) {
        fail("division by zero");
    }
    return a / b;
}

int main() {
    std::cout << port("8080") << "\n";
    try {
        port("x");
    } catch (const std::invalid_argument& e) {
        std::cout << e.what() << "\n";
    }
    std::cout << checked_div(10, 2) << "\n";
    try {
        checked_div(1, 0);
    } catch (const std::invalid_argument& e) {
        std::cout << e.what() << "\n";
    }
}
Output
8080
bad port: x
5
division by zero
  • Verdict: idiom. C++ has no bottom type. noreturn marks fail, whose type is still void. A throw expression can be one operand of ?:, and the conditional expression then has the type of the other operand, int.
JavaGitHub
public class Main {
  // Java has no bottom type, so a method that always throws uses a type variable as its result.
  static <T> T fail(String msg) {
    throw new IllegalArgumentException(msg);
  }

  static String day(int d) {
    return switch (d) {
      case 1 -> "Mon";
      case 2 -> "Tue";
      default -> throw new IllegalArgumentException("bad day " + d);
    };
  }

  public static void main(String[] args) {
    try {
      String host = args.length > 0 ? args[0] : fail("no host");
      System.out.println(host);
    } catch (IllegalArgumentException e) {
      System.out.println(e.getMessage());
    }

    System.out.println(day(1));
    try {
      day(9);
    } catch (IllegalArgumentException e) {
      System.out.println(e.getMessage());
    }

    // null fits every reference type, but not int.
    String s = null;
    Integer i = null;
    System.out.println(s + " " + i);
  }
}
Output
no host
Mon
bad day 9
null null
  • Verdict: absent. Java has no bottom type. The generic method fail returns T, so the compiler infers String for the conditional expression, but the method never returns. A switch expression allows throw in an arm, and the other arms give the value. null can be assigned to any reference type, but the null type is not a subtype of int.
#include <stdio.h>
#include <stdlib.h>

/* exit ends the process, so stop never returns to its caller. */
[[noreturn]] static void stop(const char *why) {
    printf("stop: %s\n", why);
    exit(0);
}

static int checked_div(int a, int b) {
    if (b == 0) {
        stop("division by zero");
    }
    return a / b;
}

int main(void) {
    printf("%d\n", checked_div(10, 2));
    printf("%d\n", checked_div(1, 0));
    printf("not reached\n");
    return 0;
}
Output
5
stop: division by zero
  • Verdict: idiom. C has no bottom type. noreturn, or _Noreturn in C11, says that stop does not return, and the standard functions exit and abort are declared the same way. stop still has the type void. The call checked_div(1, 0) reaches exit, so the last printf never runs.
using System;
using System.Diagnostics.CodeAnalysis;

string host = Environment.GetEnvironmentVariable("PROG_EXAMPLE_NO_SUCH_VAR") ?? "";
try
{
    string h = host.Length > 0 ? host : throw new ArgumentException("no host");
    Console.WriteLine(h);
}
catch (ArgumentException e)
{
    Console.WriteLine(e.Message);
}

Console.WriteLine(Days.Name(1));
try
{
    Days.Name(9);
}
catch (ArgumentOutOfRangeException e)
{
    Console.WriteLine(e.ParamName);
}

try
{
    Days.Port("x");
}
catch (FormatException e)
{
    Console.WriteLine(e.Message);
}

static class Days
{
    public static string Name(int d) => d switch
    {
        1 => "Mon",
        2 => "Tue",
        _ => throw new ArgumentOutOfRangeException(nameof(d)),
    };

    [DoesNotReturn]
    static void Fail(string msg) => throw new FormatException(msg);

    public static int Port(string s)
    {
        if (int.TryParse(s, out int n))
        {
            return n;
        }
        Fail("bad port: " + s);
        return 0; // still needed: DoesNotReturn does not change the result type of Fail
    }
}
Output
no host
Mon
d
bad port: x
  • Verdict: idiom. C# has no bottom type, but a throw expression can stand where a value is expected: in the conditional operator, after ??, and in an arm of a switch expression. DoesNotReturn tells the nullable analysis that Fail never returns, but Fail still has the type void, so Port needs a return after the call.
JavaScriptGitHub
// throw is a statement, so a helper function lets a throw sit inside an expression.
function fail(msg) {
  throw new Error(msg);
}

function port(s) {
  const n = Number(s);
  return Number.isInteger(n) ? n : fail("bad port: " + s);
}

console.log(port("8080"));
try {
  port("x");
} catch (e) {
  console.log(e.message);
}

const config = {};
try {
  const host = config.host ?? fail("no host");
  console.log(host);
} catch (e) {
  console.log(e.message);
}
Output
8080
bad port: x
no host
  • Verdict: absent. JavaScript has no static types, so it has no bottom type. throw is a statement and cannot be an operand of ?: or ??, so code calls a helper such as fail that always throws. In TypeScript, the result type of such a helper is never.
package main

import (
	"fmt"
	"strconv"
)

// A call to panic is a terminating statement, so no return must follow it.
func mustPort(s string) int {
	n, err := strconv.Atoi(s)
	if err == nil {
		return n
	}
	panic("bad port: " + s)
}

// A for loop without a condition and without break is a terminating statement too.
func firstNegative(ch <-chan int) int {
	for {
		if n := <-ch; n < 0 {
			return n
		}
	}
}

func main() {
	fmt.Println(mustPort("8080"))
	func() {
		defer func() {
			fmt.Println("recovered:", recover())
		}()
		mustPort("x")
	}()

	ch := make(chan int, 3)
	ch <- 1
	ch <- 2
	ch <- -1
	fmt.Println(firstNegative(ch))
}
Output
8080
recovered: bad port: x
-1
  • Verdict: idiom. Go has no bottom type. The specification makes a call to panic and an endless for loop terminating statements, so mustPort and firstNegative need no return at the end. A call to your own function that always panics does not count, so a function that ends with it still needs a return.
RustGitHub
use std::convert::Infallible;
use std::mem::size_of;
use std::panic;

// A function with the result type ! never returns.
fn fail(msg: &str) -> ! {
    panic!("{msg}")
}

fn port(s: &str) -> u16 {
    match s.parse::<u16>() {
        Ok(n) => n,
        // fail has the type !, which fits where a u16 is expected.
        Err(_) => fail(&format!("bad port: {s}")),
    }
}

fn sum_until_zero(xs: &[i32]) -> i32 {
    let mut total = 0;
    for &x in xs {
        // return and continue have the type !, so the match still has the type i32.
        let v = match x {
            n if n > 0 => n,
            0 => return total,
            _ => continue,
        };
        total += v;
    }
    total
}

fn shout(s: &str) -> Result<String, Infallible> {
    Ok(s.to_uppercase())
}

fn main() {
    panic::set_hook(Box::new(|_| {}));
    println!("{}", port("8080"));
    let err = panic::catch_unwind(|| port("x")).unwrap_err();
    println!("{}", err.downcast_ref::<String>().unwrap());

    println!("{} {}", sum_until_zero(&[3, -1, 4]), sum_until_zero(&[2, 0, 5]));

    // The Err case cannot occur, so the pattern needs only Ok.
    let Ok(name) = shout("ann");
    println!("{name} {} {}", size_of::<Result<u32, Infallible>>(), size_of::<u32>());
}
Output
8080
bad port: x
7 2
ANN 4 4
  • Verdict: native. fail has the result type !, so a call to it fits in a match arm whose other arm gives a u16. return and continue also have the type !. Infallible is the standard type with no values, so Result<u32, Infallible> has the same size as u32, and let Ok(name) = ... needs no Err case. The panic hook is replaced only to keep the panic message off the error output.
  • Bottom versus unit. The unit type has one value, so a function that returns it returns. The bottom type has none, so a function that returns it does not.
  • Inhabited bottom types. "However, when the bottom type is inhabited, it is then different from the empty type"1.
  • Uninhabited types in general. An enum with no variants, such as enum Void {} in Rust, also has no values. The Rust standard library says that a variant with such a field "can't be created and thus doesn't have to be matched"3.
  • The null type. In Java, null has a type that is a subtype of all reference types. Wikipedia lists the type of the null pointer as one use of a bottom type1. See null references.
  • Attributes instead of a type. C and C++ mark a function with noreturn. The C++ attribute "Indicates that the function will not return control flow to the calling function after it finishes (e.g. functions that terminate the application, throw exceptions, loop indefinitely, etc.)"12.

Pitfalls

  • A noreturn function that returns. In C, "If the function declared _Noreturn returns, the behavior is undefined"13. In C++, "If a function previously declared with noreturn is invoked and that invocation eventually returns, the behavior is runtime-undefined"12.
  • Python does not check Never. A function with the annotation -> Never can return None when the program runs. Only a type checker reports it, as the Python example shows.
  • never in a union disappears. In TypeScript, "Because never is a subtype of every type, it is always omitted from union types"8, so string | never is string.
  • A helper that never returns, in Go. The Go specification lists "A call to the built-in function panic" among the terminating statements14. A call to your own function that always panics, or to os.Exit, is not on that list, so a function with a result still needs a return after it. Call panic directly at the end, as the Go example does.
  • void is not bottom. A function that returns void in C, C++, Java or C# returns normally. Do not use void for a function that never returns. Use the attribute or the bottom type of the language.

Cost

The bottom type costs nothing when the program runs, because no value of it ever exists and no code after a diverging expression runs. In C and C++, noreturn is a promise to the compiler, and a program that breaks the promise has undefined behavior1312. In Rust, Result<u32, Infallible> takes no more space than u32, as the Rust example shows, and the compiler does not "require you to handle the Err case"3.

History

Pierce's 1997 report Bounded Quantification with Bottom listed the uses of a bottom type, for example "a natural type for the raise construct is raise ∈ exception -> Bot" and "List(Bot) is a good type for nil"1. In Haskell, the type is called Void, and in Scala and Kotlin Nothing1. TypeScript 2.0 added never8. Python has typing.NoReturn and, from Python 3.11, typing.Never, which "have the same meaning in the type system"4. C11 added the _Noreturn specifier, and C23 deprecated it in favor of noreturn13. C++11 added the noreturn attribute12.

References

  1. Bottom type, Wikipedia, Introduction; Relation with the empty type; Computer science applications; In programming languages
  2. Never type, The Rust Reference, type.never.intro; type.never.coercion
  3. Primitive Type never, The Rust Standard Library, Description; Never-to-any coercion
  4. typing, Python 3.14 documentation, typing.Never; typing.NoReturn; typing.assert_never
  5. Narrowing, The TypeScript Handbook, The never type; Exhaustiveness checking
  6. Nothing, Kotlin Standard Library API reference, Description
  7. Data.Void, base 4.21.0.0, Hackage, Description
  8. TypeScript 2.0 release notes, The never type
  9. Exception-handling statements, C# language reference, The throw expression
  10. DoesNotReturnAttribute Class, .NET API reference, Definition
  11. The Java Language Specification, Java SE 25 Edition, Chapter 4, 4.1 The Kinds of Types and Values
  12. C++ attribute noreturn, C++ reference, cppreference.com, Explanation
  13. _Noreturn function specifier, C reference, cppreference.com, Explanation; Standard library
  14. The Go Programming Language Specification, Terminating statements

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/249PFT/text.yaml