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.reason());
    }
}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 `ballerina run` command below.
ballerina run trap.bal
Error occurred: {ballerina}DivisionByZero

Trap

The trap unary opearator captures a panic making it possible to treat the panic as a normal error.

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.reason());
    }
}

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 `ballerina run` command below.
ballerina run trap.bal
Error occurred: {ballerina}DivisionByZero