-
Notifications
You must be signed in to change notification settings - Fork 113
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
try-catch-finally #38
Comments
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
基础
try-catch
是针对可能抛出错误代码,避免因报错而中断整体代码的运行。try
不能单独使用,必须搭配catch
或finally
使用。当
try
代码块内抛出错误时,则从该代码行起后续代码将不会执行(当前代码块),直接进入catch
。若try
没有抛出错误,则会跳过catch
。当
try
代码块内抛出错误时,但未定义catch
,即只定义了finally
,那么仍会中断整体代码的运行。无论是否抛出异常
finally
子句都会执行。即使没有catch
子句处理异常。当发生异常时,可以使用
finally
子句使您的脚本以更优雅的方式处理错误的情况。例如,释放已经绑定的资源等。嵌套
try
可以嵌套,当内部try
没有对应的catch
,则抛出的错误被最近且有定义catch
的上层所捕获。执行顺序
throw
假如以上代码块的
finally
也抛出错误,即如下:return
在 try 中加入 return 语句
从以上输出结果可看出,return 与上一小节 throw 情况类似,即
finally
优先于try
的throw
和return
。在 finally 也加入 return 语句
同上,与上一小节 throw 情况类似,finally 的 return 优先于(或取代了)
try
的return
(上一小节是 throw)。在 try 语句里抛出错误
从以上结果可看出,
try
和catch
的return
都需要先经过finally
,与throw
类似。将
return
改为throw
进行验证:可见,
throw
与return
对代码执行流程的控制是一样的。参考
The text was updated successfully, but these errors were encountered: