Ruby Basic - 9

woolim park·2021년 3월 16일
0

Ruby Basic

목록 보기
9/9
post-thumbnail

Exception

begin rescue

begin
	1 / 0 # zero division error
rescue
	puts 'Exception raised, but handled'
end

메소드 안에서 rescue 를 쓸때는 begin을 생략할 수 있다. def 가 begin 의 역할을 하기 때문이다.

def divide(x, y)
	x / y
rescue
	puts "Exceptino raised, but handled"
end

특정 예외 다루기

Exception 클래스의 서브 클래스로 받는다.

begin
	...
rescue ZeroDivisionError
	...
rescue TypeError
	...
rescue
	...
end

exception methods

=> 를 사용하면 e 객체의 메소드를 사용할 수 있다.

begin
	...
rescue ZeroDivisionError => e
	puts e.class
rescue TypeError => e
	puts e.class
rescue => e
	puts e.class
end

Exception 메소드의 종류

Exception#class
Exception#message
Exception#backtrace
Exception#full_message

raise exception

ruby exception 종류

dev even_numbers(array)
	unless array.is_a?(Array)
    	raise ArgumentError
    end
    
    if array.length == 0
    	raise StandardError.new("Too few elements")
    end
    
    array.find_all { |el| el.to_i % 2 == 0 }
end

custom exception class 만들때는 StandardError 를 상속한다. 공식문서에 보면 항상 default 로 StandardError 를 뱉는 것으로 설정되어있기 때문이다.

class TooLoudError < StandardError
	attr_reader :volume
    
	def initialize(value, msg=nil)
    	# Let parent class set message
    	super(msg || "Too loud!")
        @volume = value
    end
end

class Radio
	def volume=(value)
    	if value < 1 || value > 10
        	raise TooLoudError.new(value)
        end
        @volume = value
    end
end

begin
	r = Radio.new
    r.volume = 20
rescue TooLoudError => e
    puts "Volume #{e.volume}: #{e.message}"
end
profile
Javascript Developer

0개의 댓글