defsafe_divide(a, b) begin result = a / b puts "结果是: #{result}" rescueZeroDivisionError => e puts "错误: #{e.message}" rescueTypeError => e puts "类型错误: #{e.message}" end end
safe_divide(10, 2) # 输出: 结果是: 5 safe_divide(10, 0) # 输出: 错误: divided by 0 safe_divide(10, "a") # 输出: 类型错误: String can't be coerced into Integer
defsafe_file_open(file_name) begin file = File.open(file_name) content = file.read puts content rescueErrno::ENOENT => e puts "文件未找到: #{e.message}" ensure file.close if file # 确保文件被关闭 end end
safe_file_open("existing_file.txt") # 正常输出文件内容 safe_file_open("non_existing_file.txt") # 输出: 文件未找到: No such file or directory
deffetch_data(url) begin response = Net::HTTP.get_response(URI(url)) if response.is_a?(Net::HTTPSuccess) puts "成功获取数据: #{response.body}" else puts "请求失败: #{response.code} - #{response.message}" end rescueSocketError => e puts "网络错误: #{e.message}" rescueStandardError => e puts "其他错误: #{e.message}" end end
deffind_item(item) raiseNotFoundError.new("项目未找到") if item.nil? raisePermissionDeniedError.new("权限不足") unless has_permission?(item) item rescueMyBaseError => e puts "发生异常: #{e.message}" end
defhas_permission?(item) # 假设这里包含权限检查的逻辑 false end