import ballerina/io;
function getAccountBalance (int accountID) returns (int) | error {
    if (accountID < 100) {
        error err = {message:"Account with id:" + accountID + " is not found"};
        return err;
    } else {
        return 600;
    }
}function main (string[] args) {
    var r = getAccountBalance(24);    match r {
        int blnc => {
            io:println(blnc);
        }
        error err => {
            io:println("Error occurred: " + err.message);
        }
    }
}

Errors

Ballerina errors can both be returned as yet another return value or be thrown. Any Ballerina error type should be structurally equivalent to the error struct.

import ballerina/io;
function getAccountBalance (int accountID) returns (int) | error {

As a best practice, error will be the last return value. Its type should be ‘error’, a built-in reference type.

    if (accountID < 100) {
        error err = {message:"Account with id:" + accountID + " is not found"};
        return err;
    } else {
        return 600;
    }
}

Here we create an instance of the error struct and return. This logic is used only to explain the concept.

function main (string[] args) {
    var r = getAccountBalance(24);

Best practice is to check whether an error has occurred.

    match r {
        int blnc => {
            io:println(blnc);
        }
        error err => {
            io:println("Error occurred: " + err.message);
        }
    }
}
$ ballerina run errors.bal
Error occurred: Account with id:24 is not found