Ruby

Handling / Raising Exceptions

silveryen 2022. 9. 11. 05:12

 

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
there was an exception :(
raise는 예외를 어떻게 가져오는지에 대해서 처리하고 begin...rescue는 예외를 어떻게 반응할지에 대해 작동한다.