Skip to content

Commit

Permalink
Update check expression
Browse files Browse the repository at this point in the history
  • Loading branch information
heshanpadmasiri committed Oct 8, 2024
1 parent 0e1a3e9 commit 9db9dcf
Show file tree
Hide file tree
Showing 3 changed files with 18 additions and 14 deletions.
25 changes: 15 additions & 10 deletions examples/check-expression/check_expression.bal
Original file line number Diff line number Diff line change
@@ -1,18 +1,23 @@
import ballerina/io;

// Convert `bytes` to a `string` value and then to an `int` value.
function intFromBytes(byte[] bytes) returns int|error {

// Use `check` with an expression that may return `error`.
// If `string:fromBytes(bytes)` returns an `error` value, `check`
// makes the function return the `error` value here.
// If not, the returned `string` value is used as the value of the `str` variable.
function intFromBytesWithCheck(byte[] bytes) returns int|error {
string str = check string:fromBytes(bytes);

return int:fromString(str);
}

// Same as `intFromBytesWithCheck` but with explicit error handling.
function intFromBytesExplicit(byte[] bytes) returns int|error {
string|error res = string:fromBytes(bytes);
// Handling the error explicitly.
if res is error {
return res;
}
return int:fromString(res);
}

public function main() {
int|error res = intFromBytes([104, 101, 108, 108, 111]);
io:println(res);
int|error res1 = intFromBytesWithCheck([104, 101, 108, 108, 111]);
io:println(res1);
int|error res2 = intFromBytesExplicit([104, 101, 108, 108, 111]);
io:println(res2);
}
6 changes: 2 additions & 4 deletions examples/check-expression/check_expression.md
Original file line number Diff line number Diff line change
@@ -1,9 +1,7 @@
# Check expression

`check E` is used with an expression `E` that might result in an `error` value. If `E` results in an `error` value , then, `check` makes the function return that `error` value immediately.

The type of `check E` does not include `error`. The control flow remains explicit.
In Ballerina, it is common to write an expression that may result in an error, such as calling a function that could return an error value, checking if the result belongs to the `error` type and immediately returning that value. You can use the `check` expression to simplify this pattern.

::: code check_expression.bal :::

::: out check_expression.out :::
::: out check_expression.out :::
1 change: 1 addition & 0 deletions examples/check-expression/check_expression.out
Original file line number Diff line number Diff line change
@@ -1,2 +1,3 @@
$ bal run check_expression.bal
error("{ballerina/lang.int}NumberParsingError",message="'string' value 'hello' cannot be converted to 'int'")
error("{ballerina/lang.int}NumberParsingError",message="'string' value 'hello' cannot be converted to 'int'")

0 comments on commit 9db9dcf

Please sign in to comment.