What is an exception?
As I'm sure you've seen in RubyMonk already, it is possible for your code to generate errors, known as exceptions. When an exception occurs (Ruby calls this event "raising an exception"), it will stop processing further statements in the code and will try to escape any methods called so far. This description is a little difficult to visualize, so let's look at an example:
Notice that the code does extract Yehuda's name before it fails. But once the failure (attempting to call
nil) occurs, the program stops and further statements aren't processed. This is the first thing to do know about exceptions:
- Raising an exception halts program execution.
Are you asking yourself, "So... if program execution doesn't continue forward... where does it go?" Of course you are. The visualization of the program's execution point making a quick escape is quite close to the reality. It might add clarity to that image to know that the raised exception makes its way through all the methods called (known as the "call stack") to get to the point of failure. In the example above, the failure in
extract_first_name then propagates backward through
casual_names and finally back up to the "top", where we called
casual_names with an array. This brings us to the second thing to know about exceptions:
- A raised exception will propagate through each method in the call stack until it is stopped or reaches the point where the program started
This of course implies that exceptions can be stopped. Which brings us to our next section.