捕获所有异常

异常处理

#bash 没有异常:错误就是非 0 的退出码
throwWhenNullOrEmpty() {
    if (($# == 0)); then
        return 1
    fi
    if [[ -z $1 ]]; then
        return 2
    fi
}

#trap ... ERR 在每个失败的命令之后运行,
#相当于捕获所有错误的 catch 语句;$? 是该命令的退出码
trap 'echo "Error happened, code $?"' ERR

throwWhenNullOrEmpty
#prints "Error happened, code 1"

ls no-such-file 2> /dev/null
#prints "Error happened, code 2"

#if、while、&& 和 || 的条件中不会触发该 trap
if ! throwWhenNullOrEmpty ""; then
    echo "handled by if"
fi
#打印 "handled by if"

trap - ERR