Menu
CoddyTech

Exceptions and Validation

Lesson 23 of 48 in Coddy's Ruby for GDScript Developers course.

GDScript has no ordinary try/catch exception mechanism, so functions often return an Error code or explicit status object. Ruby uses raise and rescue, with bare rescue catching StandardError subclasses. Hash#fetch can raise KeyError for absence. An error report or exception does not automatically undo earlier mutations; validate before committing a state change when failure must leave it intact.

GDScript: complete program

extends SceneTree
func checked_double(n):
    if n < 0:
        return {"ok": false}
    return {"ok": true, "value": n * 2}
func _init():
    var result = checked_double(-2)
    if result["ok"]:
        print(result["value"])
    else:
        print("invalid")
    quit()

Ruby: complete program

begin
  puts({}.fetch("oak"))
rescue KeyError
  puts "missing"
end
puts "after"
challenge icon

Challenge

Easy

Define parse_count(text): accept exactly one or more ASCII decimal digits, then convert to an integer. Raise ArgumentError otherwise. solve strips its whole input, returns the number, or invalid when ArgumentError is raised.

Return text from solve(input) without printing. The locked driver prints the returned text with one final newline and checks required public APIs independently.

Your code goes in exercise.rb, parser.rb. main.rb holds the supplied input/output code and cannot be edited.

Try it yourself

require_relative 'exercise'
require_relative 'parser'
def check(value)
  raise 'Public API check failed' unless value
end
check(parse_count("009") == 9)
["-1", "", "2x", "4\n"].each do |s|
  begin
    parse_count(s)
    raise "Expected ArgumentError"
  rescue ArgumentError
  end
end

puts solve(STDIN.read)
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Ruby for GDScript Developers

Practice on your own: Online Ruby compiler