import ballerina/io;type Record {
int id;
string name;
};
function readRecord (Record|() value) {
var result = value;
match result{
Record rec =>{
io:println("Record ID: " + rec.id + ", value: " + rec.name);
}
(any|()) =>{
error err = {message:"Record is null"};
throw err;
}
}
}function main (string[] args) {
Record r1 = {id:1, name:"record1"};
readRecord(r1);
Record|() r2;
match r2{
Record rec =>{
io:println("Record: " + rec.name);
}
(any|()) =>{
readRecord(r2);
}
}
Record r3 = {id:3, name:"record3"};
readRecord(r3);
}
ThrowIn Ballerina, throwing an error means, something unexpected has happened that shouldn’t occur during the normal operation. A thrown error? causes the call stack to be unwound until a matching catcher is found. |
|
import ballerina/io;
|
|
type Record {
int id;
string name;
};
|
|
function readRecord (Record|() value) {
var result = value;
match result{
Record rec =>{
io:println("Record ID: " + rec.id + ", value: " + rec.name);
}
(any|()) =>{
error err = {message:"Record is null"};
throw err;
}
}
}
|
Here’s how you can throw an error. Next example shows you how to catch thrown errors. |
function main (string[] args) {
Record r1 = {id:1, name:"record1"};
readRecord(r1);
Record|() r2;
|
|
match r2{
Record rec =>{
io:println("Record: " + rec.name);
}
(any|()) =>{
readRecord(r2);
}
}
|
Record r2 is null. |
Record r3 = {id:3, name:"record3"};
readRecord(r3);
}
|
Following lines will not execute. |
$ ballerina run throw.bal
Record ID: 1, value: record1
error: error, message: record is null
at .:readRecord(throw.bal:12)
at .:main(throw.bal:20)
|
|