Exception Notes Day 1 Flashcards
what is an exception?
Exceptions are what Ruby uses to deal with errors or other unexpected events. For now it’s okay to use exception and error synonymously.
How do you design your code to handle exceptions gracefully?
by using the [begin…rescue] structure
Example:
num = 0
begin
how does the [begin…end] structure work?
The behavior of begin…rescue is this: The code in the begin block will execute until an exception is reached. Once an exception is reached, the execution will immediately jump to rescue
In the event that an exception is never hit in the begin block, then what will happen to the rescue block?
execution will never go to rescue.
Example:
num = 5
begin
What does [raise] do
raise is how we bring up an exception.
Example:
def format_name(first, last)
if !(first.instance_of?(String) && last.instance_of?(String))
raise “arguments must be strings” “Grace Hopper”
format_name(42, true) # => RuntimeError: arguments
must be strings
how do you use [raise] and [begin….rescue] together
An important distinction to note is that [raise] is how we bring up an exception, whereas [begin…rescue] is how we react to that exception.
Example:
def format_name(first, last)
if !(first.instance_of?(String) && last.instance_of?(String))
raise “arguments must be strings”
end
first.capitalize + “ “ + last.capitalize
end
first_name = 42 last_name = true begin puts format_name(first_name, last_name) rescue # do stuff to rescue the "arguments must be strings" exception... puts "there was an exception :(" end