Panic in GDScript

Our first example demonstrates how to handle unexpected errors or conditions in GDScript. While GDScript doesn’t have a direct equivalent to the panic function, we can use exceptions to achieve similar behavior.

extends Node

func _ready():
    # We'll use exceptions throughout this site to check for
    # unexpected errors. This is the only program on the
    # site designed to raise an exception.
    assert(false, "a problem")

    # A common use of exceptions is to abort if a function
    # returns an error value that we don't know how to
    # (or want to) handle. Here's an example of
    # raising an exception if we get an unexpected error when creating a new file.
    var file = File.new()
    var err = file.open("/tmp/file", File.WRITE)
    if err != OK:
        push_error("Failed to open file")
        assert(false, "File operation failed")

Running this program will cause it to raise an assertion, print an error message, and exit with a non-zero status.

When the first assertion in _ready fires, the program exits without reaching the rest of the code. If you’d like to see the program try to create a temp file, comment the first assertion out.

$ godot --script panic.gd
 SCRIPT ERROR: Assertion failed: a problem
   At: res://panic.gd:7

Note that unlike some languages which use exceptions for handling of many errors, in GDScript it is idiomatic to use error codes and the OK constant for checking success of operations wherever possible.

In GDScript, we use assert for debugging and development, and push_error for runtime error reporting. The assert function will only trigger in debug builds, while push_error will always log an error.

Remember that in a real Godot project, you would typically handle errors more gracefully, possibly using Godot’s built-in logging system or custom error handling mechanisms depending on your project’s needs.