ruby - 引发 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
解决方案
无需使用 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
推荐阅读
- c - 在链表中查找或创建元素,而不丢失头部
- eloquent - 每当在 laravel 中发生记录插入或更新时,在数据透视表中设置一个字段
- typescript - “元素”类型的参数不能分配给“HTMLElement”类型的参数
- turing-machines - 图灵机、弦和子弦
- vba - 如何在 MS Acces 中使用 VBA 更改字体大小
- c - C中不同类型的结构声明
- c# - 自定义 AuthenticationHandler 在 Asp.Net Core 3 中不起作用
- python - 使用python多处理通过迭代返回几个变量的平均值
- javascript - Javascript innerHTML 不会改变 HTML
- java - 硒左键单击的事件绑定