set_exception_handler

set_exception_handler(?callable $callback): ?callable

Installs the fallback handler for uncaught throwables (both Error and Exception implement Throwable); returns the previously installed handler (null if none); the script ends after the callback returns.

C C23

C23
#include <setjmp.h>
#include <stdio.h>

static jmp_buf escape; // the "handler" landing pad

static void go(void) {
    longjmp(escape, 1); // C has no exceptions: this is the decades-old escape hatch
}

int main(void) {
    if (setjmp(escape) == 0) {
        go();
        printf("not executed\n");
    } else {
        printf("uncaught fallback: longjmp returned to the handler\n");
    }
    return 0;
}
Output
uncaught fallback: longjmp returned to the handler

C++ C++26

C++26
#include <cstdlib>
#include <exception>
#include <iostream>
#include <stdexcept>

int main() {
    // C++: std::set_terminate is the last net when no catch exists
    std::set_terminate([]() {
        std::cout << "uncaught fallback: terminate handler reached\n";
        std::exit(0); // the default would abort() with a nonzero status
    });
    throw std::runtime_error("late failure");
}
Output
uncaught fallback: terminate handler reached

C# v11.0.100

v11.0.100
// C#: AppDomain.UnhandledException is the process-wide fallback
AppDomain.CurrentDomain.UnhandledException += (sender, e) =>
{
    var ex = (Exception)e.ExceptionObject;
    Console.WriteLine($"uncaught fallback: {ex.GetType().Name}: {ex.Message}");
    Environment.Exit(0); // the runtime would otherwise terminate with a nonzero code
};
throw new Exception("late failure");
Output
uncaught fallback: Exception: late failure

Go v1.27.4

v1.27.4
package main

import "fmt"

func go_() {
	panic("late failure")
}

func main() {
	// Go: recover inside defer is the panic fallback
	defer func() {
		if r := recover(); r != nil {
			fmt.Printf("uncaught fallback: %v\n", r)
		}
	}()
	go_()
	fmt.Println("not executed")
}
Output
uncaught fallback: late failure

Java v27.0.1

v27.0.1
public class Main {
    public static void main(String[] args) {
        // Java: Thread.setUncaughtExceptionHandler is the per-thread fallback
        Thread.currentThread().setUncaughtExceptionHandler((t, e) -> {
            System.out.println("uncaught fallback: " + e.getClass().getSimpleName() + ": " + e.getMessage());
            System.exit(0); // the JVM would otherwise exit with code 1
        });
        throw new RuntimeException("late failure");
    }
}
Output
uncaught fallback: RuntimeException: late failure

JavaScript v26.13.1

v26.13.1
// Node: process.on("uncaughtException") is the uncaught fallback
process.on("uncaughtException", (err) => {
  console.log(`uncaught fallback: ${err.name}: ${err.message}`);
});
function go() {
  throw new Error("late failure");
}
go();
console.log("not executed");
Output
uncaught fallback: Error: late failure

PHP v8.6.0

v8.6.0
// set_exception_handler installs the last-resort net for uncaught throwables
function fallback(Throwable $ex): void {
    echo "uncaught fallback: ", get_class($ex), ": ", $ex->getMessage(), "\n";
}
$previous = set_exception_handler("fallback");
var_dump($previous); // NULL - no handler was installed before
// a failure surfacing during shutdown, after the main flow completed:
register_shutdown_function(function (): void {
    throw new Exception("late failure");
});
echo "main flow completed\n";
Output
NULL
main flow completed
uncaught fallback: Exception: late failure

Python v3.15.2

v3.15.2
# Python: sys.excepthook is the uncaught-exception fallback
import sys
def fallback(exc_type, exc, tb):
    print(f"uncaught fallback: {exc_type.__name__}: {exc}")
    sys.exit(0)  # the interpreter would otherwise exit with code 1
sys.excepthook = fallback
def go():
    raise RuntimeError("late failure")
go()
print("not executed")
Output
uncaught fallback: RuntimeError: late failure

Rust v1.99.1

v1.99.1
// Rust: no global fallback - catch_unwind marks where panics may land
fn go() {
    panic!("late failure");
}

fn main() {
    std::panic::set_hook(Box::new(|_| {})); // keep the demo output clean
    let result = std::panic::catch_unwind(go);
    match result {
        Ok(_) => println!("not executed"),
        Err(_) => println!("uncaught fallback: panic caught by catch_unwind"),
    }
}
Output
uncaught fallback: panic caught by catch_unwind

TypeScript v26.13.1

v26.13.1
// TS: same mechanism as JS, with a typed handler
process.on("uncaughtException", (err: Error) => {
  console.log(`uncaught fallback: ${err.name}: ${err.message}`);
});
function go(): never {
  throw new Error("late failure");
}
go();
console.log("not executed");
Output
uncaught fallback: Error: late failure

Language differences

C: no exceptions - setjmp/longjmp is the decades-old escape hatch, but stack resources are not released automatically.

C++: the real fallback is std::set_terminate (abort by default); the idiomatic route is still try/catch.

C#: AppDomain.UnhandledException is process-wide; the process still terminates per IsTerminating afterwards - the Environment.Exit(0) in the demo is only for a clean teaching exit.

Go: no exceptions - recover must pair with panic inside defer.

Java: Thread.setUncaughtExceptionHandler is per-thread; an uncaught exception on the main thread still ends the JVM with exit code 1.

JavaScript: Node's process.on("uncaughtException") lets the process keep running after the catch - different from PHP's "must terminate after the callback" semantics; the official advice is still to log and exit.

PHP: the handler takes a Throwable; restore_exception_handler() is the sibling function, popping back to the previous handler, while set_exception_handler's return value (the old handler) can be kept for manual restoration; since PHP 8.3 the handler is detached while it runs - do not throw from inside it.

Python: sys.excepthook is the interpreter-level fallback - it prints the traceback and exits with 1 by default.

Rust: no global fallback - catch_unwind only catches panics (unwind safety boundary) and still prints the panic message by default (the demo silences it with set_hook).

TypeScript: same as JavaScript.