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.

Frequently asked questions

How does Bash & Linux handle error handling?
This task is covered in 3 stacks on this page: Bash & Linux, JavaScript, Python. The "Exit Codes & Error Handling" snippet in Bash & Linux uses `$?`.
Which command does the Bash & Linux example use?
The "Exit Codes & Error Handling" snippet uses `$?`, from the Bash Scripting section of the Bash & Linux cheat sheet.
Which stacks cover "error handling" on this page?
Bash & Linux, JavaScript, Python. Together they hold 3 copy-ready snippets for this task.
Is there anything to watch out for?
Yes. For "Exit Codes & Error Handling": $? 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.