import ballerina/io;

public function main() {
    // Calling the `divide()` function with `0` as the divisor results in a panic. A panic will cause the
    // runtime to exit. If needed, `trap` can be used to capture panics and treat them as errors thereafter.
    int|error result = trap divide(1, 0);
    if (result is int) {
        io:println("int result: ", result);
    } else {
        io:println("Error occurred: ", result.message());
    }
}

function divide(int a, int b) returns int {
    return a / b;
}

Trap

The trap expression stops a panic and gives access to the error value associated with the panic.

import ballerina/io;
public function main() {
    int|error result = trap divide(1, 0);
    if (result is int) {
        io:println("int result: ", result);
    } else {
        io:println("Error occurred: ", result.message());
    }
}

Calling the divide() function with 0 as the divisor results in a panic. A panic will cause the runtime to exit. If needed, trap can be used to capture panics and treat them as errors thereafter.

function divide(int a, int b) returns int {
    return a / b;
}
# To run this sample, navigate to the directory that contains the
# `.bal` file, and execute the `bal run` command below.
bal run trap.bal
Error occurred: {ballerina}DivisionByZero