Menu
CoddyTech

Failure as Data

Lesson 33 of 48 in Coddy's GDScript for Java Developers course.

Java supports checked and unchecked exceptions with try/catch/finally and try-with-resources. GDScript has no equivalent general recoverable exception mechanism for these tasks. Return expected rejection as bool, null, Error codes or a documented result structure. Runtime diagnostics and push_error do not implement domain results or rollback. Validate before mutation when failure must preserve state. The grader rejects stderr even if Godot exits successfully, so keep routine business rejection in the specified return contract.

Complete Java comparison. Compile all listed .java files together with Java 17, then run Main.

Java file CheckResult.java:

public record CheckResult(boolean ok,int value) {}

Java file Main.java:

public class Main { public static void main(String[] args) { CheckResult r=new CheckResult(false,3); System.out.println(r.ok()?"accepted":"rejected"); } }

Java output:

rejected

GDScript example file main.gd:

extends Node

func _ready() -> void:
	var result: Dictionary = {"ok":false,"value":3}
	print("accepted" if result["ok"] else "rejected")

GDScript output:

rejected
challenge icon

Challenge

Easy

Implement CreditBox with balance initially 5 and spend(n:int)->bool. Reject negative or unaffordable spending without changing balance. Otherwise subtract and return true. Solve returns success:balance using lowercase true/false.

Input is one JSON array on stdin. The locked main parses it, calls the public APIs and prints result= followed by the returned text and a newline. No helper should print. Independent fixed probes verify required API behavior before the input case; they do not enforce implementation style.

Your code goes in credit_box.gd, exercise.gd. main.gd holds the supplied input/output code and cannot be edited. Keep each class_name type in its named file.

Try it yourself

extends Node

func contract_ok(data: Array) -> bool:
	var box: CreditBox = CreditBox.new()
	if box.spend(-1) or box.spend(6) or box.balance != 5: return false
	if not box.spend(2) or box.balance != 3 or not box.spend(0): return false
	return true

func _ready() -> void:
	var data: Array = JSON.parse_string(OS.read_string_from_stdin())
	if not contract_ok(data):
		print("API_CONTRACT_FAILED")
		return
	print("result=" + Exercise.solve(data))
quiz iconTest yourself

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

All lessons in GDScript for Java Developers

Practice on your own: Online GDScript compiler