Monday, August 23, 2010

"RUBY" here and there_1- Using raise and rescue

I am a Novice programmer, still learning tips and tricks in the trade. Most of them are for my own reference. 

Create a file called "filename"


def fileread(filename)
    if File.exist?(filename)
       file=open(filename)
       info=file.gets          # Reads the first line and saves it to variable info
       print info
   else
       raise "Runtime Error will be raised if file is not found"
   end
end

begin
file_name=gets                 #Prompts for user input
fileread(file_name.chomp)

rescue RuntimeError
puts "Sorry the file might not be there, Please check the file again\n"

end

Now run file with "ruby"


linux-6xnc:/home/Documents/Scripts # ruby raise.rb 
/etc/passwd                         # this file exists on any unix system hahahah

Output is as below:

at:x:25:25:Batch jobs daemon:/var/spool/atjobs:/bin/bash

Lets check the same with no existing file 


linux-6xnc:/home/Documents/Scripts # ruby raise.rb 
/etc/pass
Sorry the file might not be there, Please check the file again

If we analyze the program, we are using 

raise --> to generate a RuntimeError for exception 

rescue --> With "rescue" we are displaying this exception in the way we want.







No comments:

Post a Comment