#bash has no exceptions: an error is an exit code that is not 0
throwWhenNullOrEmpty() {
if (($# == 0)); then
return 1
fi
if [[ -z $1 ]]; then
return 2
fi
}
#trap ... ERR runs after every command that fails,
#like catch for all errors; $? is the code of that command
trap 'echo "Error happened, code $?"' ERR
throwWhenNullOrEmpty
#prints "Error happened, code 1"
ls no-such-file 2> /dev/null
#prints "Error happened, code 2"
#the trap is off for the conditions of if, while, && and ||
if ! throwWhenNullOrEmpty ""; then
echo "handled by if"
fi
#prints "handled by if"
trap - ERR