Back to Examples
- Binding patterns
- Typed binding pattern
- Wildcard binding pattern
- List binding patterns
- Rest binding pattern in list binding pattern
- Mapping binding pattern
- Rest binding pattern in mapping binding pattern
- Error binding pattern
- Rest binding pattern in error binding pattern
- Single use of typed binding patterns
- Single use of typed binding patterns with on fail clause
- Iterative use of typed binding patterns
- List binding pattern in match statement
- Mapping binding pattern in match statement
- Error binding pattern in match statement
- Query expressions
- Sort iterable objects
- Let clause
- Limit clause
- Join iterable objects
- Outer Join clause
- Query tables
- Create tables with a query
- Create maps with a query
- Create streams with a query
- On conflict clause
- Advanced conflict handling
- Iterate over XML with a query
- Nested query expressions
- Destructure records using a query
- Querying streams
- Aggregation
- JSON type
- Access JSON elements
- Access optional JSON elements
- Match statement with maps
- Convert from user-defined type to JSON
- Convert from table and XML to JSON
- Convert from JSON to user-defined type
- Cast JSON to user-defined type
- Resource method typing
- JSON numbers
- JSON to record
- JSON to record with projection
- JSONPath expressions
- Asynchronous function calls
- Named workers
- Sequence diagrams
- Wait for workers
- Strands
- Named worker return values
- Alternate wait
- Multiple wait
- Named workers and futures
- Inter-worker message passing
- Alternate receive
- Multiple receive
- Conditional send
- Inter-worker failure propagation
- Named worker with on fail clause
- Synchronize message passing
- Asynchronize message passing
- Flush
- Fork
Error handling
Usually, a function handles errors by passing them up to its caller. The main
function can also return an error
value.
import ballerina/io;
// Converts `bytes` to a `string` value and then to an `int` value.
function intFromBytes(byte[] bytes) returns int|error {
string|error ret = string:fromBytes(bytes);
// The `is` operator can be used to distinguish errors from other values.
if ret is error {
return ret;
} else {
return int:fromString(ret);
}
}
// The `main` function can return an `error` value.
public function main() returns error? {
int|error res = intFromBytes([104, 101, 108, 108, 111]);
if res is error {
// The `check` expression is the shorthand for this pattern of
// checking if a value is an `error` value and it is returning that value.
return res;
} else {
io:println("result: ", res);
return;
}
}
$ bal run error_handling.balerror: {ballerina/lang.int}NumberParsingError {"message":"'string' value 'hello' cannot be converted to 'int'"}
PreviousConfigure via CLI arguments
NextCheck expression