Ruby Exceptions

Ruby Exceptions

The Ruby exceptions syntax and example.

Exceptions syntax

begin  
	--Ruby code 
rescue  
	--Ruby code    
end 

Exceptions example

begin  
	puts 'Start block'  
	raise 'Raise Error!'  
	puts 'End block'   
rescue  
	puts 'Exception Handling with rescue'  
	begin  
		puts 'Block in exception'    
	end  
end  

Output

Start block

Exception Handling with rescue

Block in exception

Exceptions example

begin  
	puts 'AAA' 
	raise 'Raise Error 1'
	puts 'BBB' 
	raise 'Raise Error 2'
rescue Exception => ex  
   puts ex.message  
end  

Output

AAA

Raise Error 1

Method with exception example

def ex_method
  begin
    raise
  rescue
    puts 'Start rescue.'  
  end
end
ex_method

Output

Start rescue.