import ballerina/log;
import ballerina/runtime;
import ballerina/io;function main (string[] args) {
int result;
try {
io:println("Start dividing numbers");
result = divideNumbers(1, 0);
} catch (error err) {
io:println("error occured: " + err.message); } finally {
io:println("finally Block executed");
}
}function divideNumbers (int a, int b) returns int {
return a / b;
}
Try/Catch/FinallyThrowing an error generally means an unexpected error has happend, and the code that handles the thrown error is not expected to be able to do much to recover from it, rather than perhaps catch and log it. Throwing errors will be very rare and will happen under exceptional circumstances such as server going out of memory, running out of disk space. |
|
import ballerina/log;
import ballerina/runtime;
import ballerina/io;
|
|
function main (string[] args) {
int result;
|
|
try {
io:println("Start dividing numbers");
|
Use a try block to surround a code segment that an error may occur. |
result = divideNumbers(1, 0);
|
Doing an operation that causes an error to be thrown |
} catch (error err) {
io:println("error occured: " + err.message);
|
A Catch block executes, when an error is thrown from the enclosing try block and the thrown error type and catch clause’s error type are matched, or if there is no match, then the catch is the first in the order, where thrown error type and catch clause’s error type are structurally equivalent. |
} finally {
io:println("finally Block executed");
}
}
|
|
function divideNumbers (int a, int b) returns int {
return a / b;
}
|
|
$ ballerina run try-catch-finally.bal
Start dividing numbers
error occured: call failed
finally Block executed
|
|