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 {
        error err = error("Record is nil");
        panic err;
    }
}public function main() {
    Record r1 = {
        id: 1,
        name: "record1"
    };
    readRecord(r1);
    Record? r2 = ();
    readRecord(r2);
    Record r3 = {
        id: 3,
        name: "record3"
    };
    readRecord(r3);
}# To run this sample, navigate to the directory that contains the
# `.bal` file, and execute the `ballerina run` command below.
ballerina run panic.bal
Record ID: 1, value: record1
error: Record is nil
        at panic:readRecord(panic.bal:13)
           panic:main(panic.bal:28)

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 {
        error err = error("Record is nil");
        panic err;
    }
}

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 `ballerina run` command below.
ballerina run panic.bal
Record ID: 1, value: record1
error: Record is nil
        at panic:readRecord(panic.bal:13)
           panic:main(panic.bal:28)