Julia Language Error cleanup


In languages such as C, the @goto statement is often used to ensure a function cleans up necessary resources, even in the event of an error. This is less important in Julia, because exceptions and try-finally blocks are often used instead.

However, it is possible for Julia code to interface with C code and C APIs, and so sometimes functions still need to be written like C code. The below example is contrived, but demonstrates a common use case. The Julia code will call Libc.malloc to allocate some memory (this simulates a C API call). If not all allocations succeed, then the function should free the resources obtained so far; otherwise, the allocated memory is returned.

using Base.Libc
function allocate_some_memory()
    mem1 = malloc(100)
    mem1 == C_NULL && @goto fail
    mem2 = malloc(200)
    mem2 == C_NULL && @goto fail
    mem3 = malloc(300)
    mem3 == C_NULL && @goto fail
    return mem1, mem2, mem3

@label fail