捕获特定异常

异常处理

#每种错误都有自己的退出码
throwWhenNullOrEmpty() {
    if (($# == 0)); then
        return 1
    fi
    if [[ -z $1 ]]; then
        return 2
    fi
}

#case 根据 $? 选择对应退出码的处理分支
throwWhenNullOrEmpty ""
case $? in
    0) echo "text is fine" ;;
    1) echo "text is not specified" ;;
    2) echo "text is empty" ;;
    *) echo "unknown error" ;;
esac
#打印 "text is empty"