java中try命令_Bash中是否有TRY CATCH命令

我在bash中开发了一个几乎完美无缺的try&catch实现,允许你编写如下代码:

try

echo 'Hello'

false

echo 'This will not be displayed'

catch

echo "Error in $__EXCEPTION_SOURCE__ at line: $__EXCEPTION_LINE__!"

你甚至可以将try-catch块嵌入其中!

try {

echo 'Hello'

try {

echo 'Nested Hello'

false

echo 'This will not execute'

} catch {

echo "Nested Caught (@ $__EXCEPTION_LINE__)"

}

false

echo 'This will not execute too'

} catch {

echo "Error in $__EXCEPTION_SOURCE__ at line: $__EXCEPTION_LINE__!"

}

代码是我bash boilerplate/framework的一部分 . 它进一步扩展了try&catch的概念,例如带有回溯和异常的错误处理(以及一些其他不错的功能) .

这是负责try&catch的代码:

set -o pipefail

shopt -s expand_aliases

declare -ig __oo__insideTryCatch=0

# if try-catch is nested, then set +e before so the parent handler doesn't catch us

alias try="[[ \$__oo__insideTryCatch -gt 0 ]] && set +e;

__oo__insideTryCatch+=1; ( set -e;

trap \"Exception.Capture \${LINENO}; \" ERR;"

alias catch=" ); Exception.Extract \$? || "

Exception.Capture() {

local script="${BASH_SOURCE[1]#./}"

if [[ ! -f /tmp/stored_exception_source ]]; then

echo "$script" > /tmp/stored_exception_source

fi

if [[ ! -f /tmp/stored_exception_line ]]; then

echo "$1" > /tmp/stored_exception_line

fi

return 0

}

Exception.Extract() {

if [[ $__oo__insideTryCatch -gt 1 ]]

then

set -e

fi

__oo__insideTryCatch+=-1

__EXCEPTION_CATCH__=( $(Exception.GetLastException) )

local retVal=$1

if [[ $retVal -gt 0 ]]

then

# BACKWARDS COMPATIBILE WAY:

# export __EXCEPTION_SOURCE__="${__EXCEPTION_CATCH__[(${#__EXCEPTION_CATCH__[@]}-1)]}"

# export __EXCEPTION_LINE__="${__EXCEPTION_CATCH__[(${#__EXCEPTION_CATCH__[@]}-2)]}"

export __EXCEPTION_SOURCE__="${__EXCEPTION_CATCH__[-1]}"

export __EXCEPTION_LINE__="${__EXCEPTION_CATCH__[-2]}"

export __EXCEPTION__="${__EXCEPTION_CATCH__[@]:0:(${#__EXCEPTION_CATCH__[@]} - 2)}"

return 1 # so that we may continue with a "catch"

fi

}

Exception.GetLastException() {

if [[ -f /tmp/stored_exception ]] && [[ -f /tmp/stored_exception_line ]] && [[ -f /tmp/stored_exception_source ]]

then

cat /tmp/stored_exception

cat /tmp/stored_exception_line

cat /tmp/stored_exception_source

else

echo -e " \n${BASH_LINENO[1]}\n${BASH_SOURCE[2]#./}"

fi

rm -f /tmp/stored_exception /tmp/stored_exception_line /tmp/stored_exception_source

return 0

}

随意使用,分叉和贡献 - 它在GitHub .

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值