aboutsummaryrefslogtreecommitdiff
path: root/doc/language/keyword/cpsc-keyword-try.7.md
blob: 611e4ba68591a18af84549042effd9a93340e8f6 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50

% CPSC-KEYWORD-TRY(7)

# NAME

cpsc-keyword-try, cpsc-keyword-catch, cpsc-keyword-endtry, cpsc-keyword-throw - catch exceptions with stack unwinding

# SYNOPSIS

```text
TRY
    statements
CATCH
    handler statements
ENDTRY

THROW
```

# DESCRIPTION

TRY, CATCH, ENDTRY, and THROW are compiler extensions to Cambridge pseudocode. Each TRY requires exactly one CATCH and an ENDTRY. CATCH takes no type or error variable; there is no error object or what() support.

Normal execution skips CATCH. An exception stops the current operation, unwinds function and procedure calls, and enters the nearest active CATCH. After the handler completes, execution continues after ENDTRY. Blocks may nest and may appear inside functions, procedures, and loops.

THROW takes no argument and always raises a new anonymous exception. An exception raised inside CATCH propagates to an enclosing TRY or a caller's handler; the same CATCH cannot catch it again. RETURN may leave either body, and leaving a handler finishes its catch state.

Runtime checks throw the same anonymous exceptions for division by zero, array index errors, null pointer dereferences, invalid enumeration values, array-parameter bounds mismatches, and file misuse. Before throwing, a runtime check prints the source line and error reason to standard error, even when CATCH handles the exception. Explicit THROW prints no diagnostic itself. Compiler errors cannot be caught. If no handler catches an exception, the program prints `Unhandled exception. Program terminated.` to standard error and returns status 1.

Arrays declared inside either body remain local to that block. Stack unwinding destroys live objects in function frames being left; objects declared in a function containing the selected CATCH remain alive until that function exits. Temporary class values are cleaned up before entering the handler. Main-level objects are destroyed only on normal program end. See [cpsc-keyword-delete(7)](cpsc-keyword-delete.7.md) for destructor and lifetime rules.

Unwinding does not automatically release internal STRING or ARRAY buffers, release keyword NEW allocations, or close files. Nightly CI runs embedded exception tests on Linux, Windows and macOS with LLVM 23.

# EXAMPLE

```text
PROCEDURE Fail()
    THROW
ENDPROCEDURE

TRY
    CALL Fail()
CATCH
    OUTPUT "Caught an exception"
ENDTRY
OUTPUT "Continuing"
```

# SEE ALSO

[cpsc-language-overview(7)](../cpsc-language-overview.7.md), [cpsc-keyword-function(7)](cpsc-keyword-function.7.md), [cpsc-keyword-procedure(7)](cpsc-keyword-procedure.7.md), [cpsc(1)](../../cpsc.1.md).