set_exception_handler

set_exception_handler(?callable $callback): ?callable

为未捕获的 Throwable(Error 与 Exception 都实现它)安装兜底处理器;返回此前安装的处理器(无则 null),回调结束后脚本终止。

C C23

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

static jmp_buf escape; //「handler」的落点

static void go(void) {
    longjmp(escape, 1); // C 没有异常:这是沿用数十年的逃生舱
}

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

C++ C++26

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

int main() {
    // C++:没有任何 catch 时 std::set_terminate 是最后的网
    std::set_terminate([]() {
        std::cout << "uncaught fallback: terminate handler reached\n";
        std::exit(0); // 默认行为是 abort() 并以非零状态结束
    });
    throw std::runtime_error("late failure");
}
输出
uncaught fallback: terminate handler reached

C# v11.0.100

v11.0.100
// C#:AppDomain.UnhandledException 是进程级兜底
AppDomain.CurrentDomain.UnhandledException += (sender, e) =>
{
    var ex = (Exception)e.ExceptionObject;
    Console.WriteLine($"uncaught fallback: {ex.GetType().Name}: {ex.Message}");
    Environment.Exit(0); // 否则运行时会以非零码终止
};
throw new Exception("late failure");
输出
uncaught fallback: Exception: late failure

Go v1.27.4

v1.27.4
package main

import "fmt"

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

func main() {
	// Go:defer 里的 recover 就是 panic 的兜底
	defer func() {
		if r := recover(); r != nil {
			fmt.Printf("uncaught fallback: %v\n", r)
		}
	}()
	go_()
	fmt.Println("not executed")
}
输出
uncaught fallback: late failure

Java v27.0.1

v27.0.1
public class Main {
    public static void main(String[] args) {
        // Java:Thread.setUncaughtExceptionHandler 是线程级兜底
        Thread.currentThread().setUncaughtExceptionHandler((t, e) -> {
            System.out.println("uncaught fallback: " + e.getClass().getSimpleName() + ": " + e.getMessage());
            System.exit(0); // 否则 JVM 会以退出码 1 结束
        });
        throw new RuntimeException("late failure");
    }
}
输出
uncaught fallback: RuntimeException: late failure

JavaScript v26.13.1

v26.13.1
// Node:process.on("uncaughtException") 即未捕获异常的兜底
process.on("uncaughtException", (err) => {
  console.log(`uncaught fallback: ${err.name}: ${err.message}`);
});
function go() {
  throw new Error("late failure");
}
go();
console.log("not executed");
输出
uncaught fallback: Error: late failure

PHP v8.6.0

v8.6.0
// set_exception_handler 为未捕获的可抛出对象安装最后一道兜底网
function fallback(Throwable $ex): void {
    echo "uncaught fallback: ", get_class($ex), ": ", $ex->getMessage(), "\n";
}
$previous = set_exception_handler("fallback");
var_dump($previous); // NULL——之前没有安装过任何 handler
// 主流程结束后、停机阶段才浮出的失败:
register_shutdown_function(function (): void {
    throw new Exception("late failure");
});
echo "main flow completed\n";
输出
NULL
main flow completed
uncaught fallback: Exception: late failure

Python v3.15.2

v3.15.2
# Python:sys.excepthook 是未捕获异常的兜底
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")
输出
uncaught fallback: RuntimeError: late failure

Rust v1.99.1

v1.99.1
// Rust:没有全局兜底——catch_unwind 标出 panic 可以落地的位置
fn go() {
    panic!("late failure");
}

fn main() {
    std::panic::set_hook(Box::new(|_| {})); // 保持演示输出干净
    let result = std::panic::catch_unwind(go);
    match result {
        Ok(_) => println!("not executed"),
        Err(_) => println!("uncaught fallback: panic caught by catch_unwind"),
    }
}
输出
uncaught fallback: panic caught by catch_unwind

TypeScript v26.13.1

v26.13.1
// TS:与 JS 同机制,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");
输出
uncaught fallback: Error: late failure

语言差异说明

C:没有异常,setjmp/longjmp 是沿用数十年的逃生舱,但栈上资源不会自动释放。

C++:真正的兜底是 std::set_terminate(默认 abort);惯用法仍是 try/catch。

C#:AppDomain.UnhandledException 是进程级事件;处理后进程仍按 IsTerminating 终止,示例的 Environment.Exit(0) 只为教学收尾。

Go:没有异常,recover 必须与 panic 在 defer 中配对。

Java:Thread.setUncaughtExceptionHandler 是线程级;主线程未捕获异常仍令 JVM 以退出码 1 结束。

JavaScript:Node 的 process.on("uncaughtException") 捕获后进程默认继续运行——与 PHP「回调后必终止」语义不同,官方仍建议记录后退出。

PHP:handler 签名收 Throwable;restore_exception_handler() 与本函数同族,弹回上一个处理器,而 set_exception_handler 的返回值(旧 handler)可留作手动恢复;PHP 8.3 起 handler 运行期间自身被卸载,请勿在其中再抛异常。

Python:sys.excepthook 是解释器级兜底,默认打印 traceback 并以 1 退出。

Rust:没有全局兜底;catch_unwind 只兜 panic(unwind 安全边界),默认仍会先打印 panic 信息(示例用 set_hook 静音)。

TypeScript:同 JavaScript。