作者godfat (godfat 真常)
看板Ruby
标题Re: [问题] rescue里头的else clause行为
时间Tue Aug 2 19:38:22 2011
※ 引述《tonytonyjan (南洋大兜虫)》之铭言:
: else clause只会在"没有任何异常掷出"时才会执行
: 意思是下面这两个写法结果是一样的:
除非你可以保证没有 exception, 不然这两段是不一样的。
但如果能保证没有 exception, 那就没有必要用 rescue 了,
所以简单地说就是这两段还是不一样的。
: ----------
: begin
: # Nothing Happens
: rescue
: else
: puts "Do something if no exceptoin was throwed."
: end
: ----------
: begin
: # Nothing Happens
: rescue
: end
: puts "Do something if no exceptin was throwed."
这个 message 是错的,因为有 exception 也会跑这段,
因为 exception 被 rescue 後就像是什麽事都没发生,
後面是会继续跑的。而在 begin rescue else 的 clause
则是一定要没有 exception 才会跑。
唯一的例外是,这边写 begin rescue 却没指定什麽
exception, 表示只接 StandardError. 比方说 SyntaxError
并不属於 StandardError, 因此单写 rescue 并无法 rescue SyntaxError.
: ----------
: 问题:
: 1. 这两种写法既然结果一样,但有没有什麽理由能让我们从中选择一个比较好的写法?
: 否则else感觉没有什麽大用
老实说,我从来没用过,想不到什麽情况下需要用
: 2. 会有else行为的争议,是因为Ruby版本的问题吗?
有什麽争议?(抱歉连结上的讨论没看 XD)
--
Hear me exalted spirits. Hear me, be you gods or devils, ye who hold
dominion here:
I am a wizard without a home. I am a wonderer seeking refuge.
Sacrifice
--
※ 发信站: 批踢踢实业坊(ptt.cc)
◆ From: 114.25.229.250