在Ruby中,處理目錄操作的異常主要使用Dir
類的相關方法,并在可能引發異常的代碼塊中使用begin-rescue
語句。以下是一些常見的目錄操作及其異常處理方法:
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
語句來捕獲可能引發的異常。每個rescue
子句都用于處理特定類型的異常,例如Errno::EEXIST
表示目錄已存在,Errno::ENOENT
表示目錄不存在等。如果沒有異常發生,程序將正常執行。如果有異常發生,程序將跳到相應的rescue
子句并執行其中的代碼。