import ballerina/io;
import ballerina/lang.'int;
function parse(string num) returns int|error {
    return 'int:fromString(num);
}function scale(string num) returns int|error {
    int x = check parse(num);
    return x * 10;
}public function main() {
    int|error w = parse("12");
    io:println(w);
    int|error x = parse("invalid");
    io:println(x);    int|error y = scale("12");
    io:println(y);    int|error z = scale("Invalid");
    io:println(z);
}# To run this sample, navigate to the directory that contains the
# `.bal` file, and execute the `ballerina run` command below.
ballerina run check.bal
12
error {ballerina/lang.int}NumberParsingError message='string' value 'invalid' cannot be converted to 'int'
120
error {ballerina/lang.int}NumberParsingError message='string' value 'Invalid' cannot be converted to 'int'

Check

The check expression is a unary expression that is used to handle errors. The check expression checks the result of the sub expression and returns if the result is of type error. Hence, check can only be used in a function which has error in its return type.

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

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

function scale(string num) returns int|error {
    int x = check parse(num);
    return x * 10;
}

The check unary operator can be used to return early on error. Here, check is used to return the error if the parse() function evaluates to error. If the actual value returned by the parse() function is an error, this function immediately returns the error, else the int value returned by parse() is set to x and execution continues. If check is used within a function, the return type of the function must include error in its return signature.

public function main() {
    int|error w = parse("12");
    io:println(w);

Passing a valid integer as a string will return an int.

    int|error x = parse("invalid");
    io:println(x);

Passing a random string will return an error.

    int|error y = scale("12");
    io:println(y);
    int|error z = scale("Invalid");
    io:println(z);
}
# To run this sample, navigate to the directory that contains the
# `.bal` file, and execute the `ballerina run` command below.
ballerina run check.bal
12
error {ballerina/lang.int}NumberParsingError message='string' value 'invalid' cannot be converted to 'int'
120
error {ballerina/lang.int}NumberParsingError message='string' value 'Invalid' cannot be converted to 'int'