1. Overview


Ruby 의 rescue는 java의 try-catch와 비슷한 문법

  • 예외가 발생할 수 있는 코드(begin) 실행하고,
  • 예외 발생하면 rescue 의 코드로 처리
begin
  # Contains may cause error
rescue (Exception class)
  # Handling error code
else
  # No error
end

만약, Method 전체에서 예외가 발생할 수 있는 경우에는, rescue 을 마지막에 작성하여 예외 처리할 수 있다.

def my_method
  # Some code may cause error
rescue (Exception class)
  # Handling error code
end

### Works but, method-level rescue is more compact
def my_method
  begin
    # Some code may cause error
  rescue (Exception class)
    # Handling error code
  end
end

Reference: StackOverflow