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)
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
| Language | Verdict | Note |
|---|---|---|
| Python | Standard library | |
| C++ | Idiom | |
| Java | Absent | |
| C | Idiom | |
| C# | Idiom | |
| JavaScript | Absent | |
| TypeScript | Native | Never 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. |
| Go | Idiom | |
| Rust | Native | |
| Kotlin | Native | Nothing has no instances, and a function that always throws has the result type Nothing. No example file exists because kotlinc is not installed. |
| SQL | Does not apply | SQL has no result type for code that does not return. A failed statement raises an error, which the database reports. |
| Bash | Does not apply | Bash has no static types, so it has no type for code that does not return. The exit builtin ends the script. |
| PowerShell | Absent | PowerShell 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. |
| HTML | Does not apply | HTML has no types of values. |
| CSS | Does not apply | CSS has no types of values in this sense. |
| Regular expressions | Does not apply | A 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.
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"])
exit code 3
None typing.Never
- Verdict: stdlib.
typing.Neverandtyping.NoReturnare the bottom type for type checkers.stopcallssys.exit, which raisesSystemExit, so the call never gives a value. Python does not check the annotation when the program runs, sobadreturnsNoneeven though its result type isNever, 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";
}
}
8080
bad port: x
5
division by zero
- Verdict: idiom. C++ has no bottom type.
noreturnmarksfail, whose type is stillvoid. Athrowexpression can be one operand of?:, and the conditional expression then has the type of the other operand,int.
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);
}
}
no host
Mon
bad day 9
null null
- Verdict: absent. Java has no bottom type. The generic method
failreturnsT, so the compiler infersStringfor the conditional expression, but the method never returns. Aswitchexpression allowsthrowin an arm, and the other arms give the value.nullcan be assigned to any reference type, but the null type is not a subtype ofint.
#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;
}
5
stop: division by zero
- Verdict: idiom. C has no bottom type.
noreturn, or_Noreturnin C11, says thatstopdoes not return, and the standard functionsexitandabortare declared the same way.stopstill has the typevoid. The callchecked_div(1, 0)reachesexit, so the lastprintfnever 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
}
}
no host
Mon
d
bad port: x
- Verdict: idiom. C# has no bottom type, but a
throwexpression can stand where a value is expected: in the conditional operator, after??, and in an arm of aswitchexpression.DoesNotReturntells the nullable analysis thatFailnever returns, butFailstill has the typevoid, soPortneeds areturnafter the call.
// 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);
}
8080
bad port: x
no host
- Verdict: absent. JavaScript has no static types, so it has no bottom type.
throwis a statement and cannot be an operand of?:or??, so code calls a helper such asfailthat always throws. In TypeScript, the result type of such a helper isnever.
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))
}
8080
recovered: bad port: x
-1
- Verdict: idiom. Go has no bottom type. The specification makes a call to
panicand an endlessforloop terminating statements, somustPortandfirstNegativeneed noreturnat the end. A call to your own function that always panics does not count, so a function that ends with it still needs areturn.
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>());
}
8080
bad port: x
7 2
ANN 4 4
- Verdict: native.
failhas the result type!, so a call to it fits in amatcharm whose other arm gives au16.returnandcontinuealso have the type!.Infallibleis the standard type with no values, soResult<u32, Infallible>has the same size asu32, andlet Ok(name) = ...needs noErrcase. The panic hook is replaced only to keep the panic message off the error output.
Variations and related ideas
- 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
-> Nevercan returnNonewhen 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 | neverisstring. - 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 areturnafter it. Callpanicdirectly at the end, as the Go example does. - void is not bottom. A function that returns
voidin C, C++, Java or C# returns normally. Do not usevoidfor 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
- Bottom type, Wikipedia, Introduction; Relation with the empty type; Computer science applications; In programming languages
- Never type, The Rust Reference, type.never.intro; type.never.coercion
- Primitive Type never, The Rust Standard Library, Description; Never-to-any coercion
- typing, Python 3.14 documentation, typing.Never; typing.NoReturn; typing.assert_never
- Narrowing, The TypeScript Handbook, The never type; Exhaustiveness checking
- Nothing, Kotlin Standard Library API reference, Description
- Data.Void, base 4.21.0.0, Hackage, Description
- TypeScript 2.0 release notes, The never type
- Exception-handling statements, C# language reference, The throw expression
- DoesNotReturnAttribute Class, .NET API reference, Definition
- The Java Language Specification, Java SE 25 Edition, Chapter 4, 4.1 The Kinds of Types and Values
- C++ attribute noreturn, C++ reference, cppreference.com, Explanation
- _Noreturn function specifier, C reference, cppreference.com, Explanation; Standard library
- 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.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H0 no proof |
|
| Lean | L0 no Lean part |
|
| Visual | V0 none |
|
| Writing | W4 complete |
|
Tag 249PFT Edit this page History Report an error Markdown