SketchUp to the rescue, stay exceptional.
We’ve just released a new article about how to use rescue in extensions.
SketchUp to the rescue, stay exceptional.
We’ve just released a new article about how to use rescue in extensions.
I give a “like” for the article.
However the snippet with the UI.inputbox is not quite as good as it could be.
Although String#to_l can raise an argument error, it is better if expecting a Numeric to use a default numeric as the default, and then let UI.inputbox raise the ArgumentError and then call retry in the rescue clause.
For example:
begin
input = UI.inputbox(["Length"], [1.to_l])
if input # false if user Cancels inputbox
length = input[0].to_l
else # avoids NoMethodError when input is false
puts "User cancelled input"
length = 1.to_l
end
rescue ArgumentError
UI.messagebox("Invalid Length")
retry
else
UI.messagebox("Length is: #{length}")
length
end
When using typed defaults, as in this example, the conversion of input[0] to a Length object is done by the UI.inputbox code so the explicit conversion in the following statement is likely not necessary (but does no harm.)
We tried to focus on the error handling and not dive into other rabbit holes in this article.
Typically when using inputbox, you should immediately return unless there is input, but that requires the code to be inside of a method. Also we see too many extensions telling the user they just cancelled when they know very well they just cancelled, so we don’t really want to encourage printing that out. We have similar issues with excessive puts. Also the input value could just as well come from a HtmlDialog or VCB as an inputbox.
I might remove in the inputbox completely in favor of a hardcoded length_input = "183 cm".
Perhaps wise as UI.inpubox has special behavior, much of which is not fully documented in the API documentation. This makes it’s proper use require special lessons.
Thomas did a good job for a lesson in his blog:
rescue => exception
There is a lot you can do with an Exception object. You can display the error message coded by the writer of the method. You can include more information and even distinctive text styling by sending the exception detailed_message. You can even ask for a backtrace context stack. It may be even possible to correct a problem and re-run the Exception’s context.