1. 기본 exception handling
begin
x = 1/0
rescue Exception
x = 0
puts( $!.class )
puts( $! )
end
puts( x )
-------실행결과-------
ZeroDivisionError
divided by 0
0
$! 는 마지막에 발생한 exception을 뜻한다.
2. exception타입에 따라 다양한 액션을 취할 수 있다.
def calc( val1, val2 )
begin
result = val1 / val2
rescue TypeError, NoMethodError => e
puts( e.class )
puts( e )
puts( "One of the values is not a number!" )
result = nil
rescue Exception => e
puts( e.class )
puts( e )
result = nil
end
return result
end
calc( 20, 0 )
puts
calc( 20, "100" )
puts
calc( "100", 100 )
-------실행결과-------
ZeroDivisionError
divided by 0
TypeError
String can't be coerced into Integer
One of the values is not a number!
NoMethodError
undefined method `/' for "100":String
One of the values is not a number!
여기서 중요한 점은 rescue의 순서이다. 만약 rescue Exception => e 코드가 먼저 나오게 된다면 TypeError나 NoMethodError가 발생하더라도 해당 블록에서 처리가 되어버릴 것이다. 왜냐하면 이 2가지 에러클래스가 Exception클래스의 자식이기 때문이다.
3. begin-else의 형태로도 사용이 가능하다.
def doCalc( aNum )
begin
result = 100 / aNum.to_i
rescue Exception => e
result = 0
msg = "Error: " + e.to_s
else
msg = "Result = #{result}"
ensure
msg = "You entered '#{aNum}'. " + msg
end
return msg
end
print( "Enter a number: " )
aNum = gets().chomp()
puts( doCalc( aNum ) )
-------실행결과-------
Enter a number: 0
You entered '0'. Error: divided by 0
** Udemy의 「Advanced Ruby Programming: 10 Steps To Mastery」를 보고 작성하였습니다.
'TIL > RUBY' 카테고리의 다른 글
루비 구조와 해석(interpretation) (0) | 2021.03.05 |
---|---|
Encapsulation and Information Hiding (0) | 2021.01.23 |
Argument (0) | 2020.12.10 |
class method (0) | 2020.12.09 |
Symbol (0) | 2020.12.05 |