Skip to reading
GDScript Programming & Godot

21. Errors, assertions and recovery

Edition 0.86.4.1 HF1

0.86.4.1 Hotfix 1 edition. Earlier lessons and screenshots retain their original version context; revised references and supplements describe the newer behavior.

Download PDFView illustrations
Code example
func parse_number(entered: String) -> Dictionary:
    if not entered.is_valid_int():
        return {"ok": false, "error": "Enter a whole number."}
    return {"ok": true, "value": entered.to_int()}
Code example
func run() -> int:
    var result: Dictionary = parse_number("42")
    return int(result.get("value", 0)) if result["ok"] else 0

GDScript does not provide try/catch exceptions. Use guards, Error codes, null checks and explicit result dictionaries. A Godot runtime error is not something PCA’s TryCall can reliably catch after it has happened.

TryCall checks whether a Callable is valid, then calls it and packages a result. It is not an exception trap. PCAAssert reports a failed condition and returns a Boolean. Native assert is a development check and is ignored in non-debug builds; do not use it as your player-facing error handling.

Figure 7. Validate catches parser problems before the record is run. Runtime logs and the Godot debugger address a different stage.

Use is_instance_valid on a Node you saved earlier, not merely node != null. A reference can still exist after the underlying object was freed.

Page 30 of 378Permalink
Go to page