Ruby 异常处理与代码块使用详解
异常处理
在 Ruby 中处理异常时, begin 关键字在某些情况下可以省略。以下是相关介绍:
省略 begin 和 end
在方法、类或模块内部捕获异常时,可以选择省略 begin 和 end 。例如:
def calc
result = 1/0
rescue Exception => e
puts( e.class )
puts( e )
result = nil
return result
end
class X
@@x = 1/0
rescue Exception => e
puts( e.class )
puts( e )
end
module Y
@@x = 1/0
rescue Exception => e
puts( e.class )
puts( e )
end
在上述所有情况下,如果按照常规方式在异常处理代码的开头和结尾放置 begin 和 end 关键字,异常处理同样有效。
catch..throw
在某些语言中,使用 catch 关键字捕获异常,使用 throw
超级会员免费看
订阅专栏 解锁全文
10

被折叠的 条评论
为什么被折叠?



