Search code examples
rubymethodsfileutils

How to handle errors from Fileutils cd


I'm having troubles when using Fileutils method in ruby

When using:

FileUtils.cd("A/non/existing/directory") 

I get an error output as expected but my ruby script violently ends.

Question is how can I prevent my ruby script from stopping when I try to access to a non existing directory?

I found this:

FileUtils.cd('/', :verbose => true)   # chdir and report it

but it doesn't work, or at least I don't know how the syntax works!


Solution

  • Your script "violently ends" because FileUtils.cd throws an exception when the directory does not exist. Because your script does not handle the exception, it exits.

    Wrap your code in a begin-rescue-block like this to handle the exception:

    require 'fileutils'
    
    begin
      FileUtils.cd "A/non/existing/directory"
    rescue Errno::ENOENT => e
      # do things for appropriate error handling
      puts e.message
    end
    

    The Errno::ENOENT exception is thrown when the directory change fails. In the rescue block you may handle the exception (here I just output the error message).