2007년 01월 28일
[루비] ruby tutorial 10 - error handling
보통 StandardError 를 subclassing 한다. 그래야 default 에도 걸리게 된다. #-------------------------------- opFile = File.open(opName, "w") while data = socket.read(512) opFile.write(data) end #-------------------------------- socket 을 이용해서 download 를 받는 code이다. 근데 이 경우 error 처리를 하고 싶을 때 어떻게 할까.
rescue try catch 와 비슷하게 쓸 수 있는 rescue 가 있다. error 가 생길 지점에서 begin 을 시작한다. 그리고 rescue 를 써서 발생하는 error 에 대한 처리를 한다. end 는 맨 마지막 모든 rescue 문을 작성한 후에 적으면 된다. #-------------------------------- opFile = File.open(opName, "w") begin # Exceptions raised by this code will # be caught by the following rescue clause while data = socket.read(512) opFile.write(data) end rescue SystemCallError $stderr.print "IO failed: " + $! opFile.close File.delete(opName) raise end #-------------------------------- 위와 같은 식으로 사용 할 수 있다. 여기서 $! 는 error 가 발생한 부분을 보여준다. 보통 에러가 나면, NameError: undefined local variable or method `string' for main:Object 이렇게 나는데, 여기서 undefined local variable or method `string' for main:Object 이부분이 $! 가 된다. #-------------------------------- begin eval string rescue SyntaxError, NameError => boom print "String doesn't compile: " + boom rescue StandardError => bang print "Error running script: " + bang end #-------------------------------- 위와 같이 rescue 를 여러개 써 넣을 수도 있다. 그러면 ruby 에서 '$!.kind_of?(parameter)'의 연산을 통해 비교하게 된다. 여기서 boom 이나 bang 은 $! 의 역할이 된다.
ensure
그리고 try catch 에 더해 final 에 해당하는 ensure 가 있다. error 가 있어서 빠지게 돼서 rescue 를 거쳤을때, rescue 를 안거칠때, 상관없다. 블럭이 끝났을 때 반드시 꼭 실행하고 싶은 것이 있다면 ensure 에 넣으면 된다. ensure 의 위치는 마지막 rescue 에 넣으면 된다.
else 라는 것도 있다. 이것은 code 에서 error 가 발생하지 않았을 때만 실행된다. 밑은 예제이다.
#-------------------------------- f = File.open("testfile") begin # .. process rescue # .. handle error else puts "Congratulations-- no errors!" ensure f.close unless f.nil? end #--------------------------------
retry rescue 에서 error 를 처리한 후에, 다시 error 를 발생시킨 곳에서 실행하고 싶을때가 있따. 보통 이런 경우는 try catch 를 잘 쓰지 않겠지만, 이것은 error 이니까, 일단 가능하다. retry 를 넣어주면 다시 begin 으로 돌아간다.
출처 : http://www.ruby-doc.org/docs/ProgrammingRuby/
# by | 2007/01/28 12:37 | 기본테마 | 트랙백 | 덧글(0)





☞ 내 이글루에 이 글과 관련된 글 쓰기 (트랙백 보내기) [도움말]