异常处理 try/catch

抛出并捕获一个异常,打印捕获到的信息。

C C23

C23
#include <stdio.h>

// C 没有异常;惯用法是"返回错误码 + 错误信息结构体"(errno 模式类似)
typedef struct {
    const char *msg;
} Error;

int may_fail(Error *err) {
    err->msg = "boom";
    return -1; // 非零返回即"抛出"
}

int main(void) {
    Error err = { NULL };
    if (may_fail(&err) != 0) { // 等价于 try/catch
        printf("caught: %s", err.msg);
    }
    return 0;
}
输出
caught: boom

C++ C++26

C++26
#include <iostream>
#include <stdexcept>
int main() {
    try {
        throw std::runtime_error("boom");
    } catch (const std::exception& e) {
        std::cout << "caught: " << e.what() << "\n";
    }
    return 0;
}
输出
caught: boom

C# v11.0.100

v11.0.100
try {
    throw new Exception("boom");
} catch (Exception e) {
    Console.WriteLine("caught: " + e.Message);
}
输出
caught: boom

Go v1.27.4

v1.27.4
package main

import (
    "errors"
    "fmt"
)

func main() {
    err := errors.New("boom")
    defer func() {
        if r := recover(); r != nil {
            fmt.Println("caught:", r)
        }
    }()
    panic(err)
}
输出
caught: boom

Java v27.0.1

v27.0.1
public class Main {
    public static void main(String[] args) {
        try {
            throw new Exception("boom");
        } catch (Exception e) {
            System.out.println("caught: " + e.getMessage());
        }
    }
}
输出
caught: boom

JavaScript v26.13.1

v26.13.1
try {
    throw new Error("boom");
} catch (e) {
    console.log("caught: " + e.message);
}
输出
caught: boom

PHP v8.6.0

v8.6.0
try {
    throw new Exception("boom");
} catch (Exception $e) {
    echo "caught: " . $e->getMessage();
}
输出
caught: boom

Python v3.15.2

v3.15.2
try:
    raise ValueError("boom")
except ValueError as e:
    print("caught:", e)
输出
caught: boom

Rust v1.99.1

v1.99.1
fn main() {
    let result: Result<(), &str> = Err("boom");
    match result {
        Ok(_) => println!("ok"),
        Err(e) => println!("caught: {}", e),
    }
}
输出
caught: boom

TypeScript v26.13.1

v26.13.1
try {
    throw new Error("boom");
} catch (e) {
    console.log("caught: " + (e as Error).message);
}
输出
caught: boom

语言差异说明

C:无异常,惯用错误码返回值(errno 模式同理;setjmp/longjmp 可模拟跨层跳转但易泄漏资源)。

C++:抛掷/捕获值类型异常,惯例按 const 引用捕获。

Go:无异常,惯用 error 返回值,panic/recover 仅用于不可恢复错误。

Java:受检异常若向外传播需在方法签名声明 throws。

JavaScript:用 throw new Error + try/catch。

PHP:用 throw new Exception + try/catch。

Python:用 raise + except。

Rust:无异常,用 Result/Option 与 ? 运算符。