diff --git a/examples/index.json b/examples/index.json index f37003bbf3..d0e4ceb86b 100644 --- a/examples/index.json +++ b/examples/index.json @@ -1376,6 +1376,13 @@ "verifyOutput": true, "isLearnByExample": true }, + { + "name": "Trap expression", + "url": "trap-expression", + "verifyBuild": true, + "verifyOutput": true, + "isLearnByExample": true + }, { "name": "Type intersection for error types", "url": "error-type-intersection", diff --git a/examples/trap-expression/trap_expression.bal b/examples/trap-expression/trap_expression.bal new file mode 100644 index 0000000000..d9736e0edb --- /dev/null +++ b/examples/trap-expression/trap_expression.bal @@ -0,0 +1,24 @@ +import ballerina/io; + +function hereBeDragons() returns int { + // Trigger a panic deep within the call stack. + alwaysPanic(); +} + +// Return type `never` indicate that this function will never return normally. That is it will always panic +function alwaysPanic() returns never { + panic error("deep down in the code"); +} + +public function main() { + // Division by 0 trigger a panic + int|error result = trap 1 / 0; + if result is error { + io:println("Error: ", result); + } + // This will tigger a panic deep within the call stack and we'll trap it here + int|error result2 = trap hereBeDragons(); + if result2 is error { + io:println("Error: ", result2); + } +} diff --git a/examples/trap-expression/trap_expression.md b/examples/trap-expression/trap_expression.md new file mode 100644 index 0000000000..6ec7ca0adf --- /dev/null +++ b/examples/trap-expression/trap_expression.md @@ -0,0 +1,9 @@ +# Trap expression + +If you have an expression such as a function call that can potentially trigger a `panic` you can use a `trap` expression to prevent further unwinding of the stack. Then if the evaluation of the expression trigger a panic you will get the `error` associated with the panic. Otherwise you will get the result of the expression. + +::: code trap_expression.bal ::: + +::: out trap_expression.out ::: + ++ [Panics](https://ballerina.io/learn/by-example/panics/) diff --git a/examples/trap-expression/trap_expression.metatags b/examples/trap-expression/trap_expression.metatags new file mode 100644 index 0000000000..da44b3deb8 --- /dev/null +++ b/examples/trap-expression/trap_expression.metatags @@ -0,0 +1,2 @@ +description: This BBE demonstrates how the trap expression is used in Ballerina to handle panics +keywords: ballerina, ballerina by example, bbe, error, panic, trap diff --git a/examples/trap-expression/trap_expression.out b/examples/trap-expression/trap_expression.out new file mode 100644 index 0000000000..d8e5f96579 --- /dev/null +++ b/examples/trap-expression/trap_expression.out @@ -0,0 +1,4 @@ +$ bal run trap_expression.bal +Error: error("{ballerina}DivisionByZero",message=" / by zero") +Error: error("deep down in the code") +