[ruby] rescue
eval()은 문자열을 수식또는 리터럴로 변환해주는데, exception이 발생할 수 있다.
자바의 try - catch 문과 동일하게 ruby는 rescue라는 문을 제공한다.
특이한 것은 모든 error와 exception을 rescue가 처리하지 않는다.
1+1 이라는 문자열을 eval()로 연산하는 코드이다.
1+1d 문자열이기 때문에 eval()시 rescue에서 syntax error 에러가 발생하는 것을 확인할 수 있다.
=> nil
>> a="1+1" ; begin ; puts eval(a) ; rescue => se ; puts "rescued!!" ; end ; puts "GOGO"
2
GOGO
=> nil
>> a="1+1d" ; begin ; puts eval(a) ; rescue => se ; puts "rescued!!" ; end ; puts "GOGO"
SyntaxError: (eval):1: syntax error, unexpected tIDENTIFIER, expecting end-of-input
from (irb):86:in `eval'
from (irb):86
from /Users/Samuel/.rbenv/versions/2.1.0/bin/irb:11:in `<main>'
이를 해결하기 위해 Exception을 명시하니까 잘 동작했다.
>> a="1+1d" ; begin ; puts eval(a) ; rescue Exception => se ; puts "rescued!!" ; end ; puts "GOGO"
rescued!!
GOGO
=> nil
>> a="1+1" ; begin ; puts eval(a) ; rescue Exception => se ; puts "rescued!!" ; end ; puts "GOGO"
2
GOGO
=> nil
참고로 StandardError 에러에 대해서는 rescue 처리를 하지 못한다.
>> a="1+1d" ; begin ; puts eval(a) ; rescue StandardError => se ; puts "rescued!!" ; end ; puts "GOGO"
SyntaxError: (eval):1: syntax error, unexpected tIDENTIFIER, expecting end-of-input
from (irb):90:in `eval'
from (irb):90
from /Users/Samuel/.rbenv/versions/2.1.0/bin/irb:11:in `<main>'