Skip to content

try catch

ffredyk edited this page Jul 23, 2026 · 1 revision

try / catch

Category

Compiler Construct (Error Handling)

Description

try/catch are compiler-level constructs for structured error handling. Code in the try block executes normally. If a throw occurs, execution jumps immediately to the catch block with the thrown value available as _exception.

How It Works

The compiler emits special opcodes for try/catch regions. The VM maintains an exception handler stack. When throw executes, the VM unwinds to the nearest enclosing try block and transfers control to its catch clause.

Usage

Basic try/catch

try {
    if (_hp <= 0) then { throw "Unit is dead"; };
    doWork();
} catch {
    systemChat f"Error: {_exception}";
};

Catch with typed error

try {
    _result = riskyOperation();
} catch {
    _error = _exception;       // SqError object
    diag_log f"Error at {_error.file}:{_error.line}";
    _result = nil;             // fallback value
};

Nested try/catch

try {
    try {
        throw "inner error";
    } catch {
        systemChat f"Inner: {_exception}";
        throw "outer error";   // re-throw
    };
} catch {
    systemChat f"Outer: {_exception}";
};

Validation with throw

_validate = {
    params ["_val", "_min", "_max"];
    if (_val < _min || _val > _max) then {
        throw f"Value {_val} out of range [{_min}, {_max}]";
    };
};

try {
    [150, 0, 100] call _validate;
} catch {
    systemChat str _exception;  // "Value 150 out of range [0, 100]"
};

The _exception variable

Inside catch, the magic variable _exception holds the thrown value. It is an SqError object with:

  • .message — the error message string
  • .file — source file path
  • .line — line number
  • .col — column number
try {
    throw "Something broke";
} catch {
    systemChat _exception.message;  // "Something broke"
    systemChat f"At {_exception.file}:{_exception.line}";
};

Thread Safety

Try/catch unwinds the current fiber only. Other fibers are unaffected.

See Also

  • throw — throw an error
  • call — synchronous execution context
  • spawn — async execution context

SQ# Wiki

Home

Engine Docs

Migration

Commands

Value Constructors

Arithmetic

Comparison

Logic

Array

String

Math

Random

Type & Introspection

HashMap

Code Execution

Concurrency

Scheduler

Thread Safety

Error

Output

Time

Multiplayer

Compiler

Clone this wiki locally