ruby中的try catch

1.在ruby中,try catch并不是用来进行异常处理的,而是一种程序流程结构,例如break,continue,go-to等

2.例如如下代码

def promptAndGet(prompt)
   print prompt
   res = readline.chomp
   throw :quitRequested if res == "!"
   puts "all ok then print"
   return res
end
 
catch :quitRequested do
   name = promptAndGet("Name: ")
   age = promptAndGet("Age: ")
   sex = promptAndGet("Sex: ")
end

promptAndGet("Name: ")

catch 定义了一个代码块,当catch内的代码发生throw时,ruby会在代码的catch块中寻找与之匹配的catch块,然后程序会回到catch结束的位置。

另外,如果发生throw,那么throw后的代码是不会执行的。

参考https://www.ibm.com/developerworks/cn/opensource/os-sixrubyfeatures/

猜你喜欢

转载自www.cnblogs.com/lshao/p/9228085.html