CBrother 异常捕获
CBrother运行时出现了异常,会直接将抛出,停止当前线程工作。如果开发者没有主动捕获异常,则会被CBrother解释器最终捕获并输出。
try catch
CBrother通过try catch来主动捕获异常
function main(parm)
{
try
{
print c;
}
catch(e)
{
print e;
}
print "main end!";
}
结果:
NotFindException:can't find 'c'
at main [testtrycatch.cb:7]
main end!
可见错误被捕获后程序继续执行,打印出了main end!
catch中的参数是字符串类型的异常信息。
finally
finally表示无论是否发生异常,finally中的代码都将被执行。
function main(parm)
{
try
{
print 1;
}
catch(e)
{
print e;
}
finally
{
print "in except finally no exception";
}
print "================================";
try
{
print c;
}
catch(e)
{
print e;
}
finally
{
print "in except finally exception";
}
print "main end!";
}
结果:
1
in except finally no exception
================================
NotFindException:can't find 'c'
at main [testtrycatch.cb:22]
in except finally exception
main end!
finally中的代码,即便是在return之后也会被执行
function main(parm)
{
try
{
return 1;
}
catch(e)
{
print e;
}
finally
{
print "in except finally no exception";
}
print "main end!";
}
结果:
in except finally no exception
出现异常时
function main(parm)
{
try
{
print c;
}
catch(e)
{
print e;
return 1;
}
finally
{
print "in except finally exception";
}
print "main end!";
}
结果:
NotFindException:can't find 'c'
at main [testtrycatch.cb:7]
in except finally exception
因为return了,main end!不会打印出来,但是finally执行了
捕获到异常时,如果catch或finally中的代码再次出现异常,则无法再次在当前函数捕获,会直接将异常抛到函数调用堆栈的上一层等待处理。