import ballerina/io;

public function main() returns error? {
    do {
        // If either `foo()` or `bar()` invocations returns an error,
        // the error will be returned from the `main` function and execution
        // of the `main` function ends.
        check foo();
        check bar();

        if !isOK() {
            // Fails explicitly with an error.
            fail error("not OK");

        }
    }
    // Failure with the respective error is caught by the `on fail` block.
    on fail var e {
        io:println(e.toString());
        return e;
    }

    return;
}

function foo() returns error? {
    io:println("OK");
    return;
}

function bar() returns error? {
    io:println("OK");
    return;
}

function isOK() returns boolean {
    // Returns `false`.
    return false;

}

Check semantics

check semantics is not to simply return on an error value. When check gets an error value, it fails. The enclosing block decides how to handle the failure. Most blocks pass the failure up to the enclosing block. Function definition handles the failure by returning the error. on fail can catch the error. fail statement is like check, but it always fails. Differs from exceptions in that control flow is explicit.

import ballerina/io;
public function main() returns error? {
    do {
        check foo();
        check bar();

If either foo() or bar() invocations returns an error, the error will be returned from the main function and execution of the main function ends.

        if !isOK() {
            fail error("not OK");

Fails explicitly with an error.

        }
    }
    on fail var e {
        io:println(e.toString());
        return e;
    }

Failure with the respective error is caught by the on fail block.

    return;
}
function foo() returns error? {
    io:println("OK");
    return;
}
function bar() returns error? {
    io:println("OK");
    return;
}
function isOK() returns boolean {
    return false;

Returns false.

}
bal run check_semantics.bal
OK
OK
error("not OK")
error: not OK