Exceptions (try/catch)
Throws and catches an exception, printing the caught message.
C C23
C23
#include <stdio.h>
// C has no exceptions; convention is "return an error code + error-info struct" (the errno pattern is similar)
typedef struct {
const char *msg;
} Error;
int may_fail(Error *err) {
err->msg = "boom";
return -1; // a non-zero return is a "throw"
}
int main(void) {
Error err = { NULL };
if (may_fail(&err) != 0) { // equivalent to try/catch
printf("caught: %s", err.msg);
}
return 0;
}
Output
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;
}
Output
caught: boom
C# v11.0.100
v11.0.100
try {
throw new Exception("boom");
} catch (Exception e) {
Console.WriteLine("caught: " + e.Message);
}
Output
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)
}
Output
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());
}
}
}
Output
caught: boom
JavaScript v26.13.1
v26.13.1
try {
throw new Error("boom");
} catch (e) {
console.log("caught: " + e.message);
}
Output
caught: boom
PHP v8.6.0
v8.6.0
try {
throw new Exception("boom");
} catch (Exception $e) {
echo "caught: " . $e->getMessage();
}
Output
caught: boom
Python v3.15.2
v3.15.2
try:
raise ValueError("boom")
except ValueError as e:
print("caught:", e)
Output
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),
}
}
Output
caught: boom
TypeScript v26.13.1
v26.13.1
try {
throw new Error("boom");
} catch (e) {
console.log("caught: " + (e as Error).message);
}
Output
caught: boom
Language differences
C: no exceptions — the idiom is error-code returns (same as the errno pattern; setjmp/longjmp can mimic long jumps but leak resources easily).
C++: throws/catches exception values, conventionally caught by const reference.
Go: no exceptions — error values are the idiom; panic/recover are reserved for unrecoverable errors.
Java: checked exceptions that propagate outward must be declared with throws on the method signature.
JavaScript: throw new Error + try/catch.
PHP: throw new Exception + try/catch.
Python: raise + except.
Rust: no exceptions — Result/Option with the ? operator.