Hackerrank Day 17: More Exceptions


A quick review on Ruby Exceptions: 

An exception is a special kind of object that indicates that something has gone wrong. When this occurs, an exception is raised (or thrown). By default, Ruby programs terminate when an exception occurs. But it is possible to declare exception handlers. An exception handler is a block of code that is executed if an exception occurs during the execution of some other block of code. Raising an exception means stopping normal execution of the program and transferring the flow-of-control to the exception handling code where you either deal with the problem that’s been encountered or exit the program completely. Which of these happens – dealing with it or aborting the program – depends on whether you have provided a rescue clause . If you haven’t provided a rescue clause, the program terminates; if you have, control flows to the rescue clause.

catch/throw are NOT the same as raise/rescue.

  • raise, failrescue, and ensure handle errors/exceptions
  • throw and catch are control flow

(Terminating a single level of control flow, like a while loop, can be done with a simple return. Terminating many levels of control flow, like a nested loop, can be done with throw.)

Unlike in other languages, Ruby’s throw and catch are not used for exceptions. Instead, they provide a way to terminate execution early when no further work is needed. (Grimm, 2011)

While the exception mechanism of raise and rescue is great for abandoning execution when things go wrong, it’s sometimes nice to be able to jump out of some deeply nested construct during normal processing. This is where catch and throw come in handy. (Thomas and Hunt, 2001)

Based on what I learned above, throw and catch should not be used in this problem because we don’t want to terminate the entire program.  We just want to raise an error for when the input does not meet criteria.

My solution: 


Also came across a pretty handy resource on Ruby gotchas and caveats.

Hackerrank Day 17: More Exceptions

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s