import ballerina/io;
import ballerina/lang.'int as ints;
function parse(string num) returns int|error {
    return ints:fromString(num);
}public function main() {
    int y = checkpanic parse("120");
    io:println(y);
    int z = checkpanic parse("Invalid");
    io:println(z);
}

Check Panic

checkpanic is a unary expression that is used to handle errors. The checkpanic expression checks the result of the sub expression and panics if the result is error. Hence, checkpanic can be considered as a built-in type-guard for errors where the program will panic if the result is an error.

import ballerina/io;
import ballerina/lang.'int as ints;
function parse(string num) returns int|error {
    return ints:fromString(num);
}

The parse() function takes a string argument and attempts to convert it to an int.

public function main() {
    int y = checkpanic parse("120");
    io:println(y);

The checkpanic unary operator can be used to terminate execution on error. Here, checkpanic is used to panic if the parse() function evaluates to error. If the actual value returned by the function is an error, the function immediately panics with the error. Passing a valid integer as a string will return an int.

    int z = checkpanic parse("Invalid");
    io:println(z);
}

Passing a random string will result in a panic.

# To run this sample, navigate to the directory that contains the
# `.bal` file, and execute the `ballerina run` command.
$ ballerina run checkpanic.bal
120
error: {ballerina/lang.int}NumberParsingError message='string' value 'Invalid' cannot be converted to 'int'
        at ballerina.lang_int:fromString(int.bal:53)
           checkpanic:parse(checkpanic.bal:6)
           checkpanic:main(checkpanic.bal:20)