首页 > 解决方案 > 引发 LoadError 时如何使用救援

问题描述

我正在尝试使用 Tk 实现文件对话框。这方面已经奏效,但我的错误检查不起作用。

由于此文件对话框只能采用某些扩展名,因此我让它引发了 LoadError,但我也不希望程序停止,我希望它重新打开以允许用户选择另一个文件。

我尝试过的每种方法都只以无限循环或 LoadError 停止程序结束。

我的代码是:

module FileExplorer
  require 'tk'
  require 'tkextlib/tile'

  def self.fileDialog
    TkClipboard.append(Tk.getOpenFile)
    f = TkClipboard.get
    begin
      unless extenstionCheck(f)
        raise LoadError, 'Please select a valid file type'
      end
    rescue LoadError
      fileDialog
    end
  end

  def self.extenstionCheck(file)
    filetypes = ['.xlsx', '.xls', '.csv', '.xml']
    type = File.extname(file)
    true if filetypes.include?(file)
  end
end

标签: rubyerror-handlingtk

解决方案


无需使用 TkClipboard,也无需使用异常。

拼写错误,“扩展名”这个词是否让您对附近检查是否filetypes包含的错误视而不见file,而不是type

你的程序,最小的改变如下,适用于我:

module FileExplorer
  require 'tk'
  require 'tkextlib/tile'

  def self.fileDialog
    while true
      f = Tk.getOpenFile
      break if extension_okay?(f)
      Tk.messageBox message: 'Please select a valid file type!', detail: "Selection was: #{f}"
    end
    f
  end

  def self.extension_okay?(file)
    filetypes = ['.xlsx', '.xls', '.csv', '.xml']
    type = File.extname(file)
    filetypes.include?(type)
  end
end
p FileExplorer.fileDialog

推荐阅读