Error handling

3 snippets across 3 stacks — Bash & Linux, JavaScript, Python

SHBash & Linux

Exit Codes & Error Handling

SH · Bash Scripting
syntax
$?
set -e
set -o pipefail
command || handle_error
example
#!/usr/bin/env bash
set -euo pipefail

grep -q 'ready' status.txt || { echo 'Not ready'; exit 1; }

if ! deploy_app; then
  echo "Deploy failed with code $?"
  rollback
  exit 1
fi

Note $? holds the exit code of the last command (0 = success, non-zero = failure). set -e aborts the script on any non-zero exit. set -u treats unset variables as errors. set -o pipefail catches failures in piped commands. Always use all three in production scripts.

JSJavaScript

try / catch / finally

JS · Error Handling
syntax
try { ... }
catch (error) { ... }
finally { ... }
example
function parseConfig(jsonString) {
  try {
    return JSON.parse(jsonString);
  } catch (error) {
    console.error("Invalid config JSON:", error.message);
    return {};
  } finally {
    console.log("Config parsing attempted.");
  }
}

const config = parseConfig('{"debug": true}');
console.log(config);
output
"Config parsing attempted."
{ debug: true }

Note finally always runs, whether the try succeeded or catch was triggered. It even runs if try or catch contains a return statement.

PYPython

try / except

PY · Error Handling
syntax
try:
    ...
except ExceptionType as e:
    ...
example
try:
    value = int("not_a_number")
except ValueError as e:
    print(f"Conversion failed: {e}")

# Multiple exception types
try:
    result = {"a": 1}["b"]
except (KeyError, IndexError) as e:
    print(f"Lookup error: {e}")
output
Conversion failed: invalid literal for int() with base 10: 'not_a_number'
Lookup error: 'b'

Note Always catch specific exceptions. Bare 'except:' catches everything including SystemExit and KeyboardInterrupt, which is almost never what you want.