Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Exceptions in Ruby

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 301
    Comment on it

    Exception is a unexpected output during execution of code in programing language. Due to exception execution of program stops.In Ruby, Exceptions are basically used to handle different type of errors, which may raise during execution of program and we cant take suitable action instead of breaking the program completely.

    Ruby handles exceptions easily. We write the code that raise an exception in between begin/end block and use rescue to tell the types of exceptions that we want to handle.

     

    Syntax :
    
    begin  
    # -  
    rescue Exception_Type_one  
    # -  
    rescue Exception_Type_two  
    # -  
    else  
    # Other Exception_Type_three
    # Default execution
    end

     

    The raised Exception against each of the params is compared by Ruby. If the match will found the exception named in the rescue clause is the same as the type of the currently thrown exception. If not found, it executes, else block.

     

    Retry ni  exception

    begin
       file = open("/notexistant_file")
       if file
          puts "File opened successfully"
       end
    rescue
       file_name = "existant_file"
       retry
    end

     

    The following is the execution of the process

     When exception occurred at open file and it went to rescue. file_name was re-assigned

    By retry went to the beginning of the begin,  this time file opens successfully and continued the other process.

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: