import ballerina/io;

type Record record {
    int id;
    string name;
};

function readRecord(Record? value) {
    if (value is Record) {
        io:println("Record ID: ", value.id, ", value: ", value.name);
    } else {
        // Panics if `value` is `()`.
        panic error("Record is nil");
    }
}

public function main() {
    Record r1 = {
        id: 1,
        name: "record1"
    };
    readRecord(r1);

    // `r2` is `()`.
    Record? r2 = ();
    // Since `r2` is `()`, `readRecord()` will panic.
    readRecord(r2);

    // The following lines of code will not be executed.
    Record r3 = {
        id: 3,
        name: "record3"
    };
    readRecord(r3);
}

Panic

In Ballerina, panic indicates abnormal completion and usually implies that something unexpected has occurred (i.e., something that should not have occurred during the normal operation). A panic causes the call stack to unwind until it is trapped, or if not trapped, results in the termination of the program.

Ballerina discourages the use of panic to handle program-related errors (such as “header not found”, “data mismatch”, etc.). However, panic can be used in scenarios such as “Connection Closed/Timeout” and “OutOfMemory” where the program cannot handle the error by itself.

import ballerina/io;
type Record record {
    int id;
    string name;
};
function readRecord(Record? value) {
    if (value is Record) {
        io:println("Record ID: ", value.id, ", value: ", value.name);
    } else {
        panic error("Record is nil");
    }
}

Panics if value is ().

public function main() {
    Record r1 = {
        id: 1,
        name: "record1"
    };
    readRecord(r1);
    Record? r2 = ();

r2 is ().

    readRecord(r2);

Since r2 is (), readRecord() will panic.

    Record r3 = {
        id: 3,
        name: "record3"
    };
    readRecord(r3);
}

The following lines of code will not be executed.

# To run this sample, navigate to the directory that contains the
# `.bal` file, and execute the `bal run` command below.
bal run panic.bal
Record ID: 1, value: record1
error: Record is nil
        at panic:readRecord(panic.bal:13)
           panic:main(panic.bal:27)