Exception Notes Day 1 Flashcards

You may prefer our related Brainscape-certified flashcards:
1
Q

what is an exception?

A

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 well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

How do you design your code to handle exceptions gracefully?

A

by using the [begin…rescue] structure
Example:
num = 0
begin

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

how does the [begin…end] structure work?

A

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

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

In the event that an exception is never hit in the begin block, then what will happen to the rescue block?

A

execution will never go to rescue.
Example:
num = 5
begin

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

What does [raise] do

A

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 well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

how do you use [raise] and [begin….rescue] together

A

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
How well did you know this?
1
Not at all
2
3
4
5
Perfectly