Skip to content

Commit

Permalink
Add panic BBE
Browse files Browse the repository at this point in the history
  • Loading branch information
heshanpadmasiri committed Oct 9, 2024
1 parent 76d3d05 commit ecdd188
Show file tree
Hide file tree
Showing 5 changed files with 46 additions and 0 deletions.
7 changes: 7 additions & 0 deletions examples/index.json
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down
24 changes: 24 additions & 0 deletions examples/trap-expression/trap_expression.bal
Original file line number Diff line number Diff line change
@@ -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);
}
}
9 changes: 9 additions & 0 deletions examples/trap-expression/trap_expression.md
Original file line number Diff line number Diff line change
@@ -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/)
2 changes: 2 additions & 0 deletions examples/trap-expression/trap_expression.metatags
Original file line number Diff line number Diff line change
@@ -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
4 changes: 4 additions & 0 deletions examples/trap-expression/trap_expression.out
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
$ bal run trap_expression.bal
Error: error("{ballerina}DivisionByZero",message=" / by zero")
Error: error("deep down in the code")

0 comments on commit ecdd188

Please sign in to comment.