Ruby에 예외처리 Begin-Rescue-Ensure관련 질문입니다

조회수 3480회

Ruby에 ensure = C#에 finally는 같은건가요?

ensure가 정확히 언제 실행되는지 몰라 파일을 언제 닫아야 할지 갈피를 못잡고 있습니다.

소스코드1

file = File.open("myFile.txt", "w")

begin
  file << "#{content} \n"
rescue
  #handle the error here
ensure
  file.close unless file.nil?
end

소스코드2

file = File.open("myFile.txt", "w")

begin
  file << "#{content} \n"
  file.close
rescue
  #handle the error here
ensure
  file.close unless file.nil?
end

1 답변

  • 좋아요

    0

    싫어요
    채택 취소하기

    ensure은 영문 그대로 "코드는 항상 evalueate될것임을 보장" 합니다. Java/C#의 finally와 똑같지요.

    보통 예외처리 begin-rescue-else-ensure-end 흐름은 이렇게 흘러갑니다

    begin
      # exception일수도 있고 아닐수도 있는 코드
    rescue SomeExceptionClass => some_variable
      # 어떤 excpetion을 처리하는 코드
    rescue SomeOtherException => some_other_variable
      # 또 다른 excpetion을 처리하는 코드
    else
      # exception이 raise되지 않은 경우 실행할 코드
    ensure
      # exception이 있던 없던 무조건 실행될 코드
    end
    

    위 흐름에서 rescue, ensure, else는 필수는 아니며, 필요한 경우 선택적으로 씁니다.

    rescue=> var부분도 꼭 적어야 하는 건 아니지만 비워뒀을 경우 정확히 어떤 exception이 발생했는지 파악하기 어려워 집니다.

    rescueexception class를 명시하지 않은 경우, StandardError를 상속받는 모든 exception이 걸러집니다(StandardError를 상속받지 않는 SystemStackError, NoMemoryError 등은 제외)


    ruby에서 특정 블록들은 exception 블록이기도 합니다. 예를들면 메소드를 정의하는 것도 exception 블록입니다. 밑의 코드1은 코드2, 코드3으로 대체할 수 있습니다.

    코드1

    def foo
      begin
        # ...
      rescue
        # ...
      end
    end
    

    코드2

    def foo
      # ...
    rescue
      # ...
    end
    

    코드3

    def foo
      # ...
    ensure
      # ...
    end
    

    (클래스/모듈 정의도 이와 같음)

답변을 하려면 로그인이 필요합니다.

프로그래머스 커뮤니티는 개발자들을 위한 Q&A 서비스입니다. 로그인해야 답변을 작성하실 수 있습니다.

(ಠ_ಠ)
(ಠ‿ಠ)