Last active
March 5, 2017 01:56
-
-
Save izabera/c1c664d542f8ef4f383c to your computer and use it in GitHub Desktop.
silly try/catch
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I really like this; I simplified it a bit for my purposes:
👍