- 论坛徽章:
- 2
|
starwing83 发表于 2012-11-21 01:19 ![]()
3. if protect(function()
-- code 1
end)(...) then
-- code 2
end
等价:
try {
-- code 1
} finially {
-- code 2
}
finally可是无论是否发生异常都会执行。 你前面的代码是这样吗?
starwing83 发表于 2012-11-21 01:19 ![]()
1. newtry(function()
-- code1
end)(function()
-- code2
end)
等价
try {
-- code2
} catch(...) {
-- code1
}
那
- try {
- // code2
- } catch (X ) {
- // code1
- } catch (Y ) {
- // code3
- }
复制代码 ?
这都不是重点。 重点是: 异常的优势不是用try/catch去代替status code。 那样没有任何优势, 反而让代码更难写。
异常的优势在于: 对不需要或者无法处理错误的地方就不去检测。
下面均假设一个代码片段无法处理错误。
- R1 r1 = acquire_r1(...);
- at_scope_exit(release_r1, r1);
- // code 1
- R2 r2 = acquire_r2(...);
- at_scope_exit(release_r2, r2);
- // code 2
- R3 r3 = acquire_r3(...);
- at_scope_exit(release_r3, r3);
- // code 3
复制代码 如果有错误发生了, 无论发生在哪个地方, 会继续往上报告。 并且动作总会被正确回滚。
Python有with, C#有using。 只有java那货才必须用try+finally(不过java8也加入了using了)。
对,它们都有一些隐性的约定。 比如close什么的。 这是无法否认的。
那么再降一级,只要支持first class function, 实现
- with_file("filename", "mode", function(file)
- -- do somthing with file
- with_connection(..., function(connection)
- -- do someting with file and connection
- end)
- end)
复制代码 并不是难事, 而且非常简单吧?
哪怕这个与传统社区里理解的异常处理不同, 但这同样可以只关注逻辑, 让能处理错误的地方去处理错误。 (当然, 和Python的with, C#/Java的using一样难免嵌套, 不像C++那样可以平级的写)。
这种pattern,Haskell做了(不过Haskell还有其他异常处理方式, 很多, 我很晕)。
甚至连scheme都做了: http://www.schemers.org/Document ... tml#%_toc_%_sec_6.6
Lua必然有这个潜力, 问题是Lua做了没有?
因为这些种种原因, 我猜测Lua社区里依然以local ok_or_result, other_result, more_result ... = f(...) 为主。
如果猜错了, 我认错, 我再也不说"Lua不支持异常了"。
如果猜对了, 哪怕说服我"Lua支持异常", 那又怎样? 就为了骗骗小朋友?
至于这个猜测准不准, 还得靠你的统计数据了, 如果你有这个闲心的话。 |
|