未发生异常时

异常处理

throwIfTrue() {
    if [[ $1 == true ]]; then
        echo "test error" >&2
        return 1
    fi
}

#if runs the command and looks at its exit code:
#0 goes to then, like else of try, any other code goes to else
if throwIfTrue true 2> /dev/null; then
    echo "else"
else
    echo "except"
fi
#printed: "except"

if throwIfTrue false; then
    echo "else"
else
    echo "except"
fi
#printed only "else"