def promptAndGet(prompt)
print prompt
res = readline.chomp
throw :quitRequested if res == "!"
return res
end
catch :quitRequested do
name = promptAndGet("Name: ")
age = promptAndGet("Age: ")
sex = promptAndGet("Sex: ")
# ..
# process information
end
promptAndGet("Name:")
From https://www.tutorialspoint.com/ruby/ruby_exceptions.htm
When executed normally, it goes through name, age, sex, and back to name again, despite the prompt only asking for the name.
Why does this happen instead of "Name" just being asked?
CodePudding user response:
That final line promptAndGet("Name")
does not get immediately executed, since it's after the catch
block.
The normal flow is that everything within the catch :quitRequested
block gets executed immediately, in order. That's why you get all 3 prompts inside. If you answer all 3 prompts, you'll also get to the prompt on the last line.
If you answer !
to any of the three prompts, the block will terminate. So you will not get the remaining prompts inside the block.
You'll still get the prompt on the last line since it's outside of the catch
.
throw
is what terminates the catch
block - not what initiates it.
Also, if you answer !
to that final prompt outside of the catch
block, you'll get an error, because the throw
was uncaught.