Skip to content

Instantly share code, notes, and snippets.

@izabera
Last active March 5, 2017 01:56
Show Gist options
  • Save izabera/c1c664d542f8ef4f383c to your computer and use it in GitHub Desktop.
Save izabera/c1c664d542f8ef4f383c to your computer and use it in GitHub Desktop.
silly try/catch
# try catch for bash/mksh/zsh/dash/busybox
[ "$BASH_VERSION" ] && shopt -s expand_aliases
alias try='tryblock ()'
alias throw='return'
alias catch='if tryblock; then :; else '
alias end_try='fi'
alias exceptions:='case $? in x) '
alias except=';;'
alias end_exceptions='esac'
alias always=' '
try {
echo a: this should run
try {
echo b: this should run
! (( RANDOM % 3 )) && throw 1 # this doesn't work in dash but that's not the point
echo c: this maybe runs
! (( RANDOM % 3 )) && throw 2
echo d: this maybe runs
throw 3
echo e: this never runs
}
catch {
exceptions:
except 1) echo exception 1
except 2) echo exception 2
except *) echo exception unknown
end_exceptions
}
always {
echo always runs
}
end_try
echo after first try block
throw 1
echo this never runs
}
catch {
echo this was caught
}
end_try
@leoj3n
Copy link

leoj3n commented Aug 17, 2016

I really like this; I simplified it a bit for my purposes:

alias try='tryblock ()'
alias catch='tryblock ||'

try {
  echo b: this should run
  return 1
  echo e: this never runs
}; catch {
  echo 'caught error'
}

👍

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment