Error Handling compared across 16 programming languages

Catch and handle errors: try/catch, exceptions, error values, or return codes.

Python JavaScript TypeScript Java C C++ C# Go Rust PHP Ruby Swift Kotlin SQL Bash HTML & CSS

PyPython

try:
    zahl = int("abc")
except ValueError as e:
    print("Invalid:", e)
finally:
    print("Cleaning up")

finally always runs – ideal for closing resources.

JSJavaScript

try {
  JSON.parse("{broken");
} catch (e) {
  console.log("Invalid:", e.name);
} finally {
  console.log("Cleaning up");
}

JavaScript has no int("abc") that raises an error (Number("abc") returns NaN); the closest analogue is JSON.parse with invalid text, which throws a SyntaxError. finally always runs.

TSTypeScript

try {
  JSON.parse("{kaputt");
} catch (e: unknown) {
  if (e instanceof Error) {
    console.log("Invalid:", e.name);
  }
} finally {
  console.log("Cleaning up");
}

In catch the error is unknown (with strict) because in JavaScript anything can be thrown – so check instanceof Error. As an analogue to int("abc"), JSON.parse with invalid text is used.

JvJava

public class Main {
    public static void main(String[] args) {
        try {
            int zahl = Integer.parseInt("abc");
            System.out.println(zahl);
        } catch (NumberFormatException e) {
            System.out.println("Invalid: " + e.getMessage());
        } finally {
            System.out.println("Cleaning up");
        }
    }
}

finally always runs. The message is: For input string: "abc". For resources, try-with-resources is even better.

CC

#include <stdio.h>
#include <errno.h>
#include <string.h>

int main(void) {
    FILE *f = fopen("does-not-exist.txt", "r");
    if (f == NULL) {
        printf("Error %d: %s\n", errno, strerror(errno));
        return 1;
    }
    fclose(f);
    return 0;
}

C has no exceptions. Functions report errors via return values (NULL, -1); the cause is in errno, and strerror turns it into text. The caller has to check every error itself.

C++C++

#include <iostream>
#include <stdexcept>
#include <string>

int main() {
    try {
        int zahl = std::stoi("abc");
        std::cout << zahl << '\n';
    } catch (const std::invalid_argument& e) {
        std::cout << "Invalid: " << e.what() << '\n';
    }   // there is no finally: cleanup is handled by RAII
}

You catch exceptions by const&. C++ has no finally; instead, destructors (RAII) clean up automatically when the block is left.

C#C#

try
{
    int zahl = int.Parse("abc");
}
catch (FormatException e)
{
    Console.WriteLine("Invalid: " + e.Message);
}
finally
{
    Console.WriteLine("Cleanup");
}

finally always runs – ideal for closing resources. Catch specific exception types such as FormatException.

GoGo

package main

import (
	"fmt"
	"strconv"
)

func main() {
	defer fmt.Println("Cleanup")
	_, err := strconv.Atoi("abc")
	if err != nil {
		fmt.Println("Invalid:", err)
	}
}

Instead of try/catch, Go uses errors as return values (if err != nil). defer always runs when the function exits – the counterpart to finally.

RsRust

fn main() {
    match "abc".parse::<i32>() {
        Ok(n) => println!("Number: {n}"),
        Err(e) => println!("Invalid: {e}"),
    }
    let ergebnis: Result<i32, String> = Err("broken".to_string());
    println!("{}", ergebnis.unwrap_or(0));
}

Instead of try/except there is Result<T, E>. Cleanup (like finally) is handled automatically by the Drop trait at the end of the scope.

PHPPHP

<?php
try {
    $x = intdiv(10, 0);
} catch (DivisionByZeroError $e) {
    echo "Error: ", $e->getMessage(), "\n";
} finally {
    echo "Cleaning up\n";
}

intdiv(10, 0) throws a DivisionByZeroError. finally always runs – ideal for closing resources.

RbRuby

begin
  Integer("abc")
rescue ArgumentError => e
  puts "Error: #{e.message}"
ensure
  puts "Cleaning up"
end

Integer("abc") raises ArgumentError (unlike "abc".to_i, which silently returns 0). ensure always runs – ideal for closing resources.

SwSwift

enum FormatFehler: Error { case keineZahl(String) }

func zahl(aus text: String) throws -> Int {
    guard let n = Int(text) else { throw FormatFehler.keineZahl(text) }
    return n
}

do {
    defer { print("Cleaning up") }
    print(try zahl(aus: "42"))
    print(try zahl(aus: "abc"))
} catch { print("Invalid:", error) }

defer runs when the block is left, even on errors, and takes over the role of finally. catch without a pattern catches everything.

KtKotlin

fun main() {
    try {
        val zahl = "abc".toInt()
        println(zahl)
    } catch (e: NumberFormatException) {
        println("Invalid: ${e.message}")
    } finally {
        println("Cleaning up")
    }
}

Kotlin has no checked exceptions. try is an expression, and finally always runs. The message is For input string: "abc".

SQLSQL

BEGIN;
INSERT INTO produkte (name, kategorie, preis) VALUES ('Tee', 'Lebensmittel', 6.20);
-- violates CHECK (preis >= 0) -> error, the transaction is unusable
INSERT INTO produkte (name, kategorie, preis) VALUES ('Error', 'Test', -1);
ROLLBACK;   -- the first INSERT is discarded as well

-- Catching errors specifically (PostgreSQL, PL/pgSQL):
-- BEGIN ... EXCEPTION WHEN check_violation THEN RAISE NOTICE 'invalid price'; END;

SQL has no try/catch: errors arise from constraints, and the database reports them to the client. Transactions replace the "cleanup": ROLLBACK undoes everything since BEGIN. Only procedural extensions (PL/pgSQL, T-SQL) have error handling in code.

shBash

#!/usr/bin/env bash
set -euo pipefail

tmp=$(mktemp)
trap 'echo "Cleaning up"; rm -f "$tmp"' EXIT

echo "working ..." > "$tmp"
cp /gibt-es-nicht "$tmp" 2> /dev/null || echo "Copy failed, continuing"
echo "done"

set -euo pipefail aborts on errors, undefined variables and pipeline failures. trap … EXIT always cleans up. With || action you deliberately catch an expected error.

</>HTML & CSS

<!DOCTYPE html>
<style>body{font:16px system-ui,sans-serif;margin:12px;background:#fff;color:#222}
input { padding: 8px; border: 2px solid #bbb; border-radius: 6px; margin-bottom: 4px; }
input:not(:placeholder-shown):invalid { border-color: #c62828; background: #fdecea; }
input:not(:placeholder-shown):valid { border-color: #2e7d32; }
.hinweis { display: none; color: #c62828; font-size: .85rem; margin: 0 0 8px; }
input:not(:placeholder-shown):invalid + .hinweis { display: block; }
</style>
<form onsubmit="event.preventDefault()">
  <input type="email" required placeholder="Enter email">
  <p class="hinweis">Please enter a valid email address.</p>
  <input type="text" required minlength="3" pattern="[A-Za-z]+" placeholder="Name (letters only, min. 3)">
  <p class="hinweis">At least 3 letters, no digits.</p>
  <button>Submit</button>
</form>

HTML forms validate themselves (required, type, pattern, minlength). The pseudo-classes :valid/:invalid make this visible; :not(:placeholder-shown) prevents empty fields from being red right away. Show an error message via the sibling selector +.

More comparisons

Hello World Variables Conditionals Loops Functions Lists and Arrays Dictionaries and Maps Classes and Objects Reading Files