Ruby目錄操作怎樣處理異常

小樊
81
2024-11-06 01:31:34

在Ruby中,處理目錄操作的異常主要使用Dir類(lèi)的相關(guān)方法,并在可能引發(fā)異常的代碼塊中使用begin-rescue語(yǔ)句。以下是一些常見(jiàn)的目錄操作及其異常處理方法:

  1. 創(chuàng)建目錄:
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
  1. 刪除目錄:
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
  1. 更改目錄:
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
  1. 列出目錄內(nèi)容:
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í)行其中的代碼。

0