RbRuby
IntermediateLesson 13 of 16

Errors, Files & JSON – Ruby

begin/rescue/ensure, custom error classes, retry, the File API and JSON.

You catch errors with begin/rescue. else runs if no error occurred, ensure runs always.

begin
  Integer("abc")
rescue ArgumentError => e
  puts "Invalid number: #{e.message}"
else
  puts "All good"
ensure
  puts "Always runs"
end

Custom error classes inherit from StandardError. With retry you repeat the begin block, e.g. for network errors.

class KontoFehler < StandardError
  def initialize(msg = "Account error")
    super
  end
end

class ZuWenigGuthaben < KontoFehler
  attr_reader :fehlbetrag

  def initialize(fehlbetrag)
    @fehlbetrag = fehlbetrag
    super("Missing #{fehlbetrag} EUR")
  end
end

def abheben(saldo, betrag)
  raise ZuWenigGuthaben.new(betrag - saldo) if betrag > saldo
  saldo - betrag
end

begin
  abheben(50, 80)
rescue KontoFehler => e
  puts "#{e.class}: #{e.message}"      # ZuWenigGuthaben: Missing 30 EUR
end

versuche = 0
begin
  versuche += 1
  raise "Network down" if versuche < 3
  puts "Success after #{versuche} attempts"
rescue
  retry if versuche < 3
  puts "Gave up"
end

def lese(pfad)
  File.read(pfad)
rescue Errno::ENOENT
  "(File missing)"
end
puts lese("gibt-es-nicht.txt")

Files: File.open with a block closes the file automatically. For small files there are shortcuts.

File.write("notizen.txt", "Line 1\nLine 2\n")
File.open("notizen.txt", "a") { |f| f.puts "Line 3" }
puts File.read("notizen.txt")
File.foreach("notizen.txt") { |z| puts z.chomp.upcase }
puts File.readlines("notizen.txt", chomp: true).inspect   # ["Line 1", "Line 2", "Line 3"]
puts File.exist?("notizen.txt"), File.extname("a/b.rb"), File.basename("a/b.rb", ".rb")
File.delete("notizen.txt")

JSON is part of the standard library:

require "json"

daten = { name: "Ada", sprachen: ["Ruby", "C"] }
json = JSON.pretty_generate(daten)
puts json
zurueck = JSON.parse(json, symbolize_names: true)
puts zurueck[:sprachen].first      # Ruby
WarningNever write rescue Exception: it also catches Interrupt (Ctrl+C) and system errors. A rescue => e only catches StandardError and its children – that is almost always right.
TipWithout an error class (rescue alone), only StandardError is caught as well. raise "Text" raises a RuntimeError; custom classes make errors specifically catchable.