在Ruby中,處理目錄操作的異常主要使用Dir
類(lèi)的相關(guān)方法,并在可能引發(fā)異常的代碼塊中使用begin-rescue
語(yǔ)句。以下是一些常見(jiàn)的目錄操作及其異常處理方法:
begin
Dir.mkdir("new_directory")
rescue Errno::EEXIST => e
puts "Directory already exists: #{e.message}"
rescue SystemStackError => e
puts "Stack level too deep: #{e.message}"
rescue => e
puts "An unexpected error occurred: #{e.message}"
end
begin
Dir.rmdir("new_directory")
rescue Errno::ENOENT => e
puts "Directory does not exist: #{e.message}"
rescue Errno::ENOTDIR => e
puts "Not a directory: #{e.message}"
rescue SystemStackError => e
puts "Stack level too deep: #{e.message}"
rescue => e
puts "An unexpected error occurred: #{e.message}"
end
begin
Dir.chdir("new_directory")
rescue Errno::ENOENT => e
puts "Directory does not exist: #{e.message}"
rescue SystemStackError => e
puts "Stack level too deep: #{e.message}"
rescue => e
puts "An unexpected error occurred: #{e.message}"
end
begin
Dir.entries("new_directory")
rescue Errno::ENOENT => e
puts "Directory does not exist: #{e.message}"
rescue SystemStackError => e
puts "Stack level too deep: #{e.message}"
rescue => e
puts "An unexpected error occurred: #{e.message}"
end
在這些示例中,我們使用了begin-rescue
語(yǔ)句來(lái)捕獲可能引發(fā)的異常。每個(gè)rescue
子句都用于處理特定類(lèi)型的異常,例如Errno::EEXIST
表示目錄已存在,Errno::ENOENT
表示目錄不存在等。如果沒(méi)有異常發(fā)生,程序?qū)⒄?zhí)行。如果有異常發(fā)生,程序?qū)⑻较鄳?yīng)的rescue
子句并執(zhí)行其中的代碼。